Search code examples
excelvbainitializationdeclare

Initialize and call variables


I am trying to create a macro in excel using visual basic. I am running into a problem when I am trying to call my variables. I have never coded in visual basic before so I not sure if I am initializing and calling all of my variables correctly.

Here is the code I'm working with:

Sub Graphing2()
'
' Graphing2 Macro
'

'
    Dim a, b, y, x As Long
    a = 176
    b = 126
    y = 3
    x = 0
    Do While x < 225
    ActiveSheet.ChartObjects("Chart 1").Activate
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.FullSeriesCollection(2).Name = "=""Unit y"""
    ActiveChart.FullSeriesCollection(2).XValues = "=Sheet1!$B$a:$B$b"
    ActiveChart.FullSeriesCollection(2).Values = "=Sheet1!$E$a:$E$b"
    x = x + 1
    y = y + 1
    a = a + 67
    b = b + 67
    Loop
End Sub

Any help on how to initialize and then call variables would be helpful. Thanks


Solution

  • Untested but some pointers here:

    Sub Graphing2()
        'must specify type for each variable....
        Dim a As Long, b As Long, y As Long, x As Long
        Dim cht As Chart 'declare a chart variable
        
        a = 176
        b = 126
        y = 3
        
        Set cht = ActiveSheet.ChartObjects("Chart 1").Chart
        
        'user a For Next loop for fixed sequences
        For x = 0 To 244
            
            With cht.SeriesCollection.NewSerie 'NewSeries returns the added series
                'concatenate your variables
                .Name = "Unit " & y
                .XValues = "=Sheet1!$B$" & a & ":$B$" & b
                .Values = "=Sheet1!$E$" & a & ":$E$" & b
            End With
            
            y = y + 1
            a = a + 67
            b = b + 67
        Next x
    End Sub