excelvbaloopsfor-loop

Loop VBA Microsoft Excel


Private Sub UserForm_Activate()
If ActiveSheet.Range("AK4").Value = 0 Then
    CXBTN1.Value = False
ElseIf ActiveSheet.Range("AK4").Value = "FALSE" Then
    CXBTN1.Value = False
Else
    CXBTN1.Value = True
End If

'CheckBox
If ActiveSheet.Range("AL4").Value = 0 Then
    CXBTN2.Value = False
ElseIf ActiveSheet.Range("AL4").Value = "FALSE" Then
    CXBTN2.Value = False
Else
    CXBTN2.Value = True
End If
End Sub

Is there a way I can loop through this? I'm doing it manually. I can't seem to find the loop for this.


Solution

  • Like this:

    celladdrs = Array("AK4", "AL4") 'extend as needed
    ctls= Array(CXBTN1, CXBTN2)
    for i = 0 to 1
        addr = celladdrs(i)
        ' Use "Set" for object assignment!
        Set control = ctls(i)
        If ActiveSheet.Range(addr).Value = 0 Then
            control.Value = False
        ElseIf ActiveSheet.Range(addr).Value = "FALSE" Then
            control.Value = False
        Else
            control.Value = True
        End If
    Next