早上好,我正在寻找一个VBA代码,该代码将在excel工作表中搜索现有的命令按钮,如果找不到,则会添加它们。这是我到目前为止的内容:
Sub test()
Dim objBtn As OLEObject, r As Range
Dim cell As Range
For Each cell In Range("C11:I21")
If cell.Value = "button name" Then found = True
Next cell
If Not found Then
Set objBtn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, _
DisplayAsIcon:=False, Left:=100, Top:=100, Width:=90, Height:=30)
objBtn.Object.Caption = "button caption"
End If
End Sub
问题是我正在查看单元格内部,而按钮实际上不是,它们是上述单元格的一种。那么我该如何寻找他们呢?一张照片,显示命令按钮的外观:
答案 0 :(得分:0)
在Oleobjects集合中循环浏览,您可以在工作表中列出一个现有按钮的列表,然后在缺少按钮时采取行动;
Sub test()
Dim x As OLEObject, s As String, YourButtons() As Variant, btn As Variant, objBtn As OLEObject
YourButtons = Array("CommandButton1", "CommandButton5", "CommandButton3", "CommandButton4")
With Sheet1
For Each x In .OLEObjects
If TypeName(x.Object) = "CommandButton" Then
s = s & "|" & x.Name
End If
Next
For Each btn In YourButtons
If InStr(1, s, btn, vbTextCompare) = 0 Then
Set objBtn = .OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, _
DisplayAsIcon:=False, Left:=100, Top:=100, Width:=90, Height:=30)
objBtn.Object.Caption = "button caption"
End If
Next btn
End With
End Sub