Search code examples
excelvbacall

Run function several times VBA


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.


Solution

  • 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