如果您使用它,它将为您提供一些更动态地命名按钮的功能。但是,由于您使用 ActiveCell 来放置它,如果您尝试一次创建它们,则会导致它们全部重叠。如果您可以详细说明按钮的放置位置,它们是否相同,或者是什么决定了它们的位置,我可以提供更多细节。
Dim lCount As Long
lCount = 1
Set newButton = ActiveSheet.Buttons.Add( _
ActiveCell.Left, _
ActiveCell.Top, _
ActiveCell.Offset(0, 1).Range("A1:C2").Width, _
ActiveCell.Offset(0, 1).Range("A1:A3").Height)
With newButton
.Name = "Button" & lCount 'The actual button name.
.Caption = newButton.Name 'This is the DISPLAY on the button.
End With
另一种方法是省略 lCount,只在代码中命名按钮。这将涉及您激活所需的单元格,然后运行代码,并将 .Name 属性中的值从 1 更改为 2、3 等。
With newButton
.Name = "Button1" 'The actual button name.
.Caption = newButton.Name 'This is the DISPLAY on the button.
End With
您可以有一个隐藏的工作表(例如“HiddenHelper”)来跟踪您创建了多少按钮并让 lCount 引用该单元格。当您清除工作表时,您将该值也重置回 1。然后当您添加另一个按钮时,让代码将 1 添加到单元格值,以跟踪您使用了多少,如下所示:
Dim lCount As Long
lCount = Sheets("HiddenHelper").Range("A1")
Set newButton = ActiveSheet.Buttons.Add( _
ActiveCell.Left, _
ActiveCell.Top, _
ActiveCell.Offset(0, 1).Range("A1:C2").Width, _
ActiveCell.Offset(0, 1).Range("A1:A3").Height)
With newButton
.Name = "Button" & lCount 'The actual button name.
.Caption = newButton.Name 'This is the DISPLAY on the button.
End With
Sheets("HiddenHelper").Range("A1") = Sheets("HiddenHelper").Range("A1") + 1
当然,您可以随意命名帮助表,并将按钮数量的范围设置为适合您的任何名称。