mardi 17 avril 2018

vba excel If condition error on final iteration

I'm having the code takes the input from my checkboxes and grab data from the related worksheet. I ran it line by line and found out that it always gets a runtime error at the If statement on the final loop. Is there something wrong in my code?

Option Explicit

Private Sub UserForm_Initialize()
    Dim counter As Long
    Dim chkBox  As MSForms.CheckBox

    ''''Add checkboxes based on total sheet count
    For counter = 1 To Sheets.count - 2
        Set chkBox = Me.Frame1.Controls.Add("Forms.CheckBox.1", "CheckBox" & counter)
        chkBox.Caption = Sheets(counter + 2).Name
        chkBox.Left = 10
        chkBox.Top = 5 + ((counter - 1) * 20)
    Next

End Sub

Private Sub cmdContinue_Click()

    Dim Series As Object
    Dim counter As Long

    '''Clear old series
    For Each Series In Sheets(2).SeriesCollection
        Sheets(2).SeriesCollection(1).Delete
    Next


    ''Cycle through checkboxes
    For counter = 1 To Sheets.count - 2
        ''If the box is checked then
        If Me.Frame1.Controls(counter).Value = True Then ''Error here on 4th iteration
            ''Add new series
            With Sheets(2).SeriesCollection.NewSeries
                .Name = Sheets(counter + 2).Range("$A$1")
                .XValues = Sheets(counter + 2).Range("$A$12:$A$25")
                .Values = Sheets(counter + 2).Range("$B$12:$B$25")
            End With

        End If

    Next counter

    Me.Hide

End Sub

Also, a second problem is it always run on the wrong loop. If i check box 2 it'll run data for the box 1 sheet, 3 run for 2, 4 run for 3, and 1 run for 4. Can anyone explain the reason behind this?

Aucun commentaire:

Enregistrer un commentaire