1

I'm rewriting some code and had a thought, but can't seem to get my syntax right to execute it properly. I want to use a for loop to populate an array of commandbuttons as well as control their visibility. I just need help with my syntax to define which CommandButton number I'm working on in the loop. For instance, CommandButton1, CommandButton2, etc.

Public Sub LoadLots(sName As String, streamLots() As String)
    Label1.Caption = sName
    For o = 1 To 9
        If streamLots(o) <> "" Then
            CommandButton& o &.Caption = streamLots(o)
            CommandButton& o & .Visable = True
        Else
            CommandButton& o & .Visable = False
        End If
    Next
End Sub
3
  • 2
    Activesheet.Shapes("CommandButton" & o).Caption ... also Visable should be Visible Commented Jul 24, 2016 at 21:29
  • I should have added, these buttons are on a form. Commented Jul 24, 2016 at 21:36
  • same principle, but you got the answer below as well. Commented Jul 24, 2016 at 23:52

1 Answer 1

1

Use the Userform.Controls collection to reference the commandbuttons by name.

Public Sub LoadLots(sName As String, streamLots() As String)
    Dim btn As MSForms.CommandButton
    Label1.Caption = sName
    For o = 1 To 9
        Set btn = Me.Controls("CommandButton" & o)
        If streamLots(o) <> "" Then
            btn.Caption = streamLots(o)
            btn.Visible = True
        Else
           btn.Visible = False
        End If
    Next
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I was able to help. Thanks for the check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.