我正在尝试使用Excel VBA创建新的ActiveX控件命令按钮。我有一个过去工作过的循环VBA,theFile1.1.xlsm具有工作簿的主列表。我需要在〜3200个工作簿中添加一个CommandButton,因此我将使用Do-Loop宏。这是循环代码供参考。
Sub Macro2()
Application.ScreenUpdating = False
Dim sFile As String
Dim wb As Workbook
Dim FileName1 As String
Dim FileName2 As String
Dim wksSource As Worksheet
Const scWkbSourceName As String = "theFILE 1.1.xlsm"
Set wkbSource = Workbooks(scWkbSourceName)
Set wksSource = wkbSource.Sheets("Sheet1") ' Replace 'Sheet1' w/ sheet name of SourceSheet
Const wsOriginalBook As String = "theFILE 1.1.xlsm"
Const sPath As String = "E:\ExampleFolder\"
SourceRow = 5
Do While Cells(SourceRow, "D").Value <> ""
Sheets("Sheet1").Select
FileName1 = wksSource.Range("A" & SourceRow).Value
FileName2 = wksSource.Range("K" & SourceRow).Value
sFile = sPath & FileName1 & "\" & FileName2 & ".xlsm"
Set wb = Workbooks.Open(sFile)
''insert code for loop operation
'''CLOSE WORKBOOK W/O BEFORE SAVE
Application.EnableEvents = False
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.EnableEvents = True
SourceRow = SourceRow + 1
Loop
End Sub
我想将按钮设置为变量(我认为),因此我可以编辑格式/属性,并希望以后向该按钮添加宏。
Dim buttonControl As MSForms.CommandButton
Set buttonControl = _
ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Link:=False, _
DisplayAsIcon:=False, _
Left:=1464, Top:=310, Width:=107.25, Height:=30)
With buttonControl.Opject
.Caption = "OPEN FOLDER"
.Name = "cmd_OPEN_FOLDER"
End With
我遇到“运行时错误13:类型不匹配”错误。我不确定为什么,因为在正确的位置创建了“ CommandButton1”。
答案 0 :(得分:4)
OLEObjects.Add
创建一个OLEObject
并将其添加到OLEObjects
集合中; Add
函数返回的对象是OLEObject
,而不是MSForm.CommandButton
。这是OLEObject.Object
的基础类型-因此,请将您的buttonControl
设置为返回对象的.Object
属性:
Set buttonControl = _
ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Link:=False, _
DisplayAsIcon:=False, _
Left:=1464, Top:=310, Width:=107.25, Height:=30).Object
在正确的位置创建了按钮,因为Add
函数可以工作并返回-类型不匹配的失败之处在于将返回的OLEObject
分配给了CommandButton
变量,该操作结束后。
随后的With
块可以只是With buttonControl
。