I've created a VBA Macro for word template and I want to associate it to a button(Graphics button, Not keyboard buttons).There are basically two ways to create a macro :
1) Using macro recorder
2) Using VBA for application to write macro from scratch
But I found several issues with these ways :
I tried First one, What I want is to execute a macro on a button onclick event. but in that I am not getting how to assign that macro to that button.
For second option I tried following procedure :
Goto VB by pressing Alt + F11. On the Tools menu, click References. Select the reference for Microsoft Visual Basic for Applications Extensibility. Insert a new module, and then add the following code example.
Sub Test()
'Add a command button to a new document
Dim doc As Word.Document
Dim shp As Word.InlineShape
Set doc = Documents.Add
Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
shp.OLEFormat.Object.Caption = "Click Here"
'Add a procedure for the click event of the inlineshape
'**Note: The click event resides in the This Document module
Dim sCode As String
sCode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()" & vbCrLf & _
" MsgBox ""You Clicked the CommandButton""" & vbCrLf & _
"End Sub"
doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString sCode
End Sub
This is the code for macro creation through Vb.But here error is coming in secondlast line of code.
Can anyone suggest me how to get an executable macro on a button click? Am I doing any mistakes in above code?