JMG
JMG

Reputation: 3

Add a commandbutton with a macro assigned

In ms Word how do I use VBA to add a CommandButton and assign it a macro (still using VBA)?

I have code to add the command button. How do I automatically add a macro to it without adding a private sub each time I run the first macro?

Sub CompareCase()

Dim testname As String
Dim test1, test2, test3

test1 = ""
test2 = ""
test3 = ""

testname = LCase(InputBox("Enter name of test.")

Call SelectAndProcess

Select Case testname

Case "string1"
    ActiveDocument.compare Name:=test1, DetectFormatChanges:=False, CompareTarget:=wdCompareTargetOriginal

Case "string2"
    ActiveDocument.compare Name:=test2, DetectFormatChanges:=False, CompareTarget:=wdCompareTargetOriginal

Case "string3"
    ActiveDocument.compare Name:=test3, DetectFormatChanges:=False, CompareTarget:=wdCompareTargetOriginal

Case Else
    MsgBox "Test not found"

End Select

Call Macro_Add_Button

End Sub

I'd like to assign the CommandButton a macro upon creation.

Sub Macro_Add_Button()

Dim oCtl
Dim oCmd

ActiveDocument.Content.InsertParagraphAfter

Set oCtl = ActiveDocument.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1", Range:=ActiveDocument.Paragraphs.Last.Range)

Set oCmd = oCtl.OLEFormat.Object

oCmd.Caption = "Score"

End Sub

Upvotes: 0

Views: 355

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25693

The problem with your idea is that an MSForms control on the document surface is considered an object belonging to the document. As such, the code it links to must be in the ThisDocument module and its name must be the name of the control followed by an underscore and click: CommandButton1_Click.

If you need more flexibility then consider using a MacroButton field. You can assign a (inline) graphic that looks like a button as the "display text". And your code can change the ButtonFieldClicks property (Application.Options.ButtonFieldClicks) to one (1) so that it triggers on a single rather than on the default double-click. A MacroButton field can be assigned to any "Public Sub" procedure.

Upvotes: 0

Related Questions