R
RC - S
I am trying to add a CommandButton via VBA to a new document created by the
VBA. I have tried the Microsoft suggested solution to do this add but as
soon as the CommandButton is loaded with the code...Word Crashes, every time.
When it recovers, the button actually works when it is clicked.
as soon as the F8 button (run manually) is clicked and the code moves to the
last (or any other line i put in it) line and dumps Word.
Here is the code:
Private Sub CommandButton1_Click()
'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
You should be able to clip this into your own doc to see it happen.
if someone can help with the coding or some other means to achieve the
presence of a button on a document my template creates, i would be happy to
hear from you.
Best regards
VBA. I have tried the Microsoft suggested solution to do this add but as
soon as the CommandButton is loaded with the code...Word Crashes, every time.
When it recovers, the button actually works when it is clicked.
as soon as the F8 button (run manually) is clicked and the code moves to the
last (or any other line i put in it) line and dumps Word.
Here is the code:
Private Sub CommandButton1_Click()
'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
You should be able to clip this into your own doc to see it happen.
if someone can help with the coding or some other means to achieve the
presence of a button on a document my template creates, i would be happy to
hear from you.
Best regards