我想用按钮替换一些单元格值,但清除该值会阻止添加下一个按钮。这是脚本:
Private Sub Workbook_Open()
Dim Sh As Worksheet
Dim btn As Button
Dim cell As Range
For Each Sh In ActiveWorkbook.Worksheets
For Each cell In Sh.UsedRange.Cells
If cell.Value = "{magic_value}" Then
Set btn = Sh.Buttons.Add(cell.Left, cell.Top, cell.Width, cell.Height)
With btn
.OnAction = "ButtonClickHandler"
.Caption = "Btn_" & cell.Left & "_" & cell.Top
.Name = "Btn_" & cell.Left & "_" & cell.Top
End With
cell.ClearContents ' everything works without this line
End If
Next
Next
End Sub
当我打开工作簿时,会添加第一个按钮但不会显示下一个按钮,并且会出现Runtime error '1004'
:Unable to get property Add of class Buttons
(我的翻译)。调试器指向行Set btn = Sh.Buttons.Add ...
根据我的研究,原因是行cell.ClearContents
。但我无法想象错误与细胞清除有什么关系。
答案 0 :(得分:1)
对不起,问题出现在我没有告诉你的代码中:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Sh.Unprotect pwd
Target.Locked = False
Sh.Protect pwd
End Sub
更新单元格的值引发了SheetChange事件。我的解决方案是暂时禁用事件:
Application.EnableEvents = False
For Each Sh In ActiveWorkbook.Worksheets
...
Application.EnableEvents = True
答案 1 :(得分:1)
虽然您的代码在我的计算机上运行得非常好,但我可以理解Button
集合是否存在问题。如果您进入对象浏览器,您将看到隐藏了Button
集合。我不确定这个集合是否会被折旧。然而,它在过去也给我带来了一些问题。为什么不试试这个:
Dim Sh As Worksheet
Dim cell As Range
For Each Sh In ActiveWorkbook.Worksheets
For Each cell In Sh.UsedRange.Cells
If cell.Value = "{magic_value}" Then
Sh.Shapes.AddFormControl(xlButtonControl, cell.Left, cell.Top, cell.EntireColumn.Width, cell.EntireRow.Height).Name = _
"Btn_" & cell.Left & "_" & cell.Top
Sh.Shapes("Btn_" & cell.Left & "_" & cell.Top).OnAction = "ButtonClickHandler"
cell.ClearContents ' everything works without this line
End If
Next
Next
此(上述)案例中的名称和标题相同,并且on_click操作会自动分配给这些表单控件。