VBA Variable as CommandButton#

强颜欢笑 提交于 2021-02-17 02:48:51

问题


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

回答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


来源:https://stackoverflow.com/questions/38556935/vba-variable-as-commandbutton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!