so I've created a Macro which writes a new Macro to Sheet1 of the VBA editor, then creates the ActiveX Control CommandButton. Now I need the button to run the newly created macro when clicked upon. The Button has been created as a Object Variable called '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
I now have a 'Run-time error 438: Object doesn't support this property or method' on
Selection.OnAction = "cmd_OPEN_FOLDER_Click()" 'assigns the macro
When I end the VBA from the Dialog Box and click on the newly button it seamed to have associated correctly. How does one do this without the error message?
Selection. You have abuttonControl, just set itsOnActionproperty. You're getting error 438 becauseSelectionisn't the button (and there's no need to select it anyway). Or... waaaaait a minute - isn'tOnActionfor Forms Controls, not ActiveX? Why not use any shape then? I often use a rounded-corner rectangle shape in place of a button. Looks much prettier!MyButton, you need to have aMyButton_Click()procedure in that worksheet's code-behind, and it should "just work".