在ms Word中,如何使用VBA添加CommandButton并为其分配宏(仍使用VBA)?
我有添加命令按钮的代码。如何在每次运行第一个宏时自动向其添加宏而不添加私有子集?
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
我想在创建时为CommandButton分配一个宏。
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
您的想法的问题在于,文档表面上的MSForms控件被视为属于文档的对象。因此,它链接到的代码必须在ThisDocument模块中,并且它的名称必须是控件的名称,后跟一个下划线,然后单击:CommandButton1_Click。
如果需要更大的灵活性,请考虑使用MacroButton字段。您可以将看起来像按钮的(嵌入式)图形分配为“显示文本”。并且您的代码可以将ButtonFieldClicks属性(Application.Options.ButtonFieldClicks)更改为一(1),以使其在单次触发而不是默认的双击触发。可以将MacroButton字段分配给任何“公共子”过程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句