Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming and referring to a chart in VBA

I am trying to create charts in excel using VBA . The code is as follows :

Sub testmacro()    
    Dim i As Integer     
    i = Sheets("Data").Range("M2").Value
  Sheets("Email ID").Activate
    Range("A1").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlColumnClustered

    If i = 1 Then  
        ActiveChart.SetSourceData Source:=Range("Data!$E$1:$F$3")        
    ActiveChart.SeriesCollection(1).Select
    With Selection.Format.Fill
       .
       .
       .        
    End If     

    If i = 2 Then

   End if

   If i=3 Then  

    End If   

End Sub

Now, I want to be able to perform the actions when i=2 and i=3 on the same chart i created when i=1

However, I am not able to do so.

So can anyone help me how to give a name for the chart i created when i=1 and be able to refer to it whie i=2 and i=3??

like image 936
kira Avatar asked Dec 20 '22 01:12

kira


2 Answers

Kira, you can change the chart name by code using:

yourchart.Name = "Name"

Or in the worksheet you can select the chart, go to the Layout Tab and in the right edge there will be a text box saying Chart Name

then you can refer to it in your vba code using

Worksheets("yoursheet").ChartObjects("Name").PropertyYouWant
like image 130
Pedro Braz Avatar answered Dec 31 '22 09:12

Pedro Braz


Here is a way to assign a name to a chart:

Sub dural()
    Dim ch As Shape
    Range("A1").Select
    ActiveSheet.Shapes.AddChart.Select
    Set ch = ActiveSheet.Shapes(1)
    ch.Name = "First Chart"
End Sub
like image 41
Gary's Student Avatar answered Dec 31 '22 07:12

Gary's Student