使用Excel VBA将宏关联到Commandbutton变量

时间:2018-12-20 19:11:56

标签: excel vba excel-vba activex activexobject

所以我创建了一个宏,该宏将新的宏写入VBA编辑器的Sheet1中,然后创建ActiveX控件命令按钮。现在,我需要在单击该按钮时运行新创建的宏。按钮已创建为名为“ buttonControl”的对象变量。

Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Sheet1")
Set CodeMod = VBComp.CodeModule
    With CodeMod
        .InsertLines 34, "Private Sub cmd_OPEN_FOLDER_Click()"
        .InsertLines 35, "    Dim FolderPath As String"
        .InsertLines 36, "    Dim FinalFolder As String"
        .InsertLines 37, "        FolderPath = ""C:\ExampleFolder1\ExampleFolder2\"""
        .InsertLines 38, "        FinalFolder = ActiveSheet.Range(""N1"").Value & ""\"""
        .InsertLines 39, "    Call Shell(""explorer.exe """""" & FolderPath & FinalFolder & """", vbNormalFocus)"
        .InsertLines 40, "End Sub"

    End With

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).Object

    With buttonControl
        .Caption = "OPEN FOLDER"
        .Name = "cmd_OPEN_FOLDER"
        .BackColor = "12713921"
        Selection.OnAction = "cmd_OPEN_FOLDER_Click()" 'assigns the macro

    End With

我现在在

上遇到“运行时错误438:对象不支持此属性或方法”
        Selection.OnAction = "cmd_OPEN_FOLDER_Click()" 'assigns the macro

当我从对话框中结束VBA并单击新按钮时,它似乎已正确关联。没有错误信息怎么办?

1 个答案:

答案 0 :(得分:4)

这对我来说很好。 OnAction不适用于ActiveX按钮-您将子名称命名为与按钮名称加“ _Click”相符

Sub tester()

    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim CodeMod As VBIDE.CodeModule
    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents("Sheet1")
    Set CodeMod = VBComp.CodeModule

    With CodeMod
        .InsertLines 34, "Private Sub cmd_OPEN_FOLDER_Click()"
        .InsertLines 34, "Msgbox ""OK"""
        .InsertLines 40, "End Sub"
    End With

    Dim buttonControl 'As MSForms.CommandButton

    Set buttonControl = _
        ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
            Link:=False, _
            DisplayAsIcon:=False, _
            Left:=10, Top:=10, Width:=107.25, Height:=30)

    buttonControl.Name = "cmd_OPEN_FOLDER"
    With buttonControl.Object
        .Caption = "OPEN FOLDER"
        .BackColor = 12713921
    End With
End Sub