VBA变量为CommandButton#

时间:2016-07-24 21:22:24

标签: excel vba excel-vba

我正在重写一些代码并进行了思考,但似乎无法使我的语法正确执行它。我想使用for循环来填充一组命令按钮以及控制它们的可见性。我只需要帮助我的语法来定义我在循环中正在处理的CommandButton编号。例如,CommandButton1,CommandButton2等

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 个答案:

答案 0 :(得分:2)

使用Userform.Controls集合按名称引用命令按钮。

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