Run function several times VBA

50 Views Asked by At

I want to call a function several time (with differents values) when I click on a button. But when I click on it, the function run 1 time (for chart 7 in the example) and then stop. The function don't continue (for chart 3 in the example). Any idea why?

Here is what my code looks like:

Public Sub CommandButton1_Click()
    Sheets("Sheet1").ChartObjects("Chart 7").Activate
    Call changechart(Range("F2:G11"), "Title 1")

    Sheets("Sheet1").ChartObjects("Chart 3").Activate
    Call changechart(Range("A11:B18"), "Title 2")
End Sub
Sub changechart(x As Range, T As String)
    ActiveChart.ChartTitle.Text = T
    ActiveChart.SetSourceData Source:=Sheets("Sheet2").x
End Sub

I tried to put all functions in a master function instead of in the commandbutton1_click: same result.

2

There are 2 best solutions below

0
VBasic2008 On BEST ANSWER

Change Chart

Public Sub CommandButton1_Click()
    With ThisWorkbook.Sheets("Sheet1")
        ChangeChart .ChartObjects("Chart 7"), "F2:G11", "Title 1"
        ChangeChart .ChartObjects("Chart 3"), "A11:B18", "Title 2"
    End With
End Sub
Sub ChangeChart( _
        ByVal cho As ChartObject, _
        ByVal RangeAddress As String, _
        ByVal Title As String)
    With cho.Chart
        .ChartTitle.Text = Title
        .SetSourceData Source:=ThisWorkbook.Sheets("Sheet2").Range(RangeAddress)
    End With
End Sub
0
taller On
  • Sheets("Sheet2").x doesn't work.
  • Your code only changes ChartTitle of chart 7, then SetSourceData raises error.
Option Explicit

Public Sub CommandButton1_Click()
    Call Changechart("Chart 7", "F2:G11", "Title 1")
    Call Changechart("Chart 3", "A11:B18", "Title 2")
End Sub
Sub Changechart(ByVal sCht As String, ByVal sSrc As String, ByVal T As String)
    With Sheets("Sheet1").ChartObjects(sCht)
        .ChartTitle.Text = T
        .SetSourceData Source:=Sheets("Sheet2").Range(sSrc)
    End With
End Sub