2

我正在尝试编写代码以根据单元格值使多个按钮可见

我有 10 个命令按钮都是不可见的,我只想显示第一个 x x 是“Sheet1”中单元格“A1”的值(将从 1 到 10)命令按钮名称是默认名称(CommandButton4、CommandButton5、.. . , 命令按钮 13)

注意:我正在使用工作表而不是用户表单

这是我的代码,但我需要更短、更专业、更高效的代码

Private Sub CommandButton15_Click()
    Dim i As Long
    Dim CommandButton() As Variant

    Application.ScreenUpdating = False

    CommandButton = Array("CommandButton4", "CommandButton5", "CommandButton6", "CommandButton7",     "CommandButton8", "CommandButton9", "CommandButton10", "CommandButton11", "CommandButton12", "CommandButton13")

    For i = LBound(CommandButton) To LBound(CommandButton) + Sheet1.Range("A1").Value - 1

        Sheet1.Shapes(CommandButton(i)).Visible = True

    Next i

    Application.ScreenUpdating = True

End Sub

需要你的帮助请

4

1 回答 1

2

如评论中所述,您应该重命名按钮。这只是让事情变得更容易。

例如,您可以将它们命名为“btn1”、“btn2”、“btn3”...。您的代码没问题,我看不到重大错误。我不知道您以后是否要添加新按钮。

如果是这样,我会推荐一些更通用的东西。如果您将按钮重命名为“btn1”...那么您可以使用以下内容:

Private Sub CommandButton15_Click()
Dim btn As OLEObject, name As String, i As Long
i = Sheets(1).Range("A1").Value + 1
For Each btn In ActiveSheet.OLEObjects
    name = btn.name
    If btn.OLEType = xlButtonOnly And InStr(name, "btn") = 1 Then
        If Int(Right(name, Len(name) - 3)) < i Then
            btn.Visible = True
        Else
            btn.Visible = False
        End If
    End If
Next
End Sub

因此,您可以添加新按钮并使用“btn..”模式命名它们,而无需更改代码。

于 2013-06-11T08:43:23.367 回答