如何解决VBA在word中鼠标右键点击添加宏
我在 Office 365 中运行 Word;我有一个宏,我可以通过添加到功能区的按钮运行它,但这需要访问它正在运行的机器(至少,我是这样做的),并且该文件将分发给分布式劳动力。>
我正在尝试在文档中编写一个宏,该宏将在您右键单击文本选择时出现的下拉菜单中添加一个按钮,但下面的代码没有向菜单添加任何内容。
Sub AddToShortcut()
Dim Bar As CommandBar
Dim NewControl As CommandBarButton
DeleteFromShortcut
Set Bar = Application.CommandBars("Standard")
Set NewControl = Bar.Controls.Add(Type:=msoControlButton,ID:=1,Temporary:=True)
With NewControl
.Caption = "&New Action"
.OnAction = "AddAction"
.Style = msoButtonIconAndCaption
End With
End Sub
Private Sub document_open()
'adds the right-click shortcut when the document opens
Call AddToShortcut
End Sub
我从 John Walkenbach 的 Excel VBA Programming for Dummies 中获得了代码的核心,所以我认为 Word 和 Excel 的操作方式之间存在一些差异导致问题?
解决方法
您想将其添加到“文本”上下文菜单,而不是“标准”。
,以下直接来自Greg Maxey's page,你说太多了。不过,这就是答案。您的代码大约是 oBtn。
您会将其放入存储在您的 Global Template (指向我的页面的链接) 中的 Word Startup Folder 中。它可以重命名为 AutoExec 或从该模板中的 AutoExec 过程调用。
Option Explicit
Dim oPopUp As CommandBarPopup
Dim oCtr As CommandBarControl
Sub BuildControls()
Dim oBtn As CommandBarButton
'Make changes to the Add-In template
CustomizationContext = ThisDocument.AttachedTemplate
'Prevent double customization
Set oPopup = CommandBars.FindControl(Tag:="custPopup")
If Not oPopup Is Nothing Then GoTo Add_Individual
'Add PopUp menu control to the top of the "Text" short-cut menu
Set oPopUp = CommandBars("Text").Controls.Add(msoControlPopup,1)
With oPopUp
.Caption = "My Very Own Menu"
.Tag = "custPopup"
.BeginGroup = True
End With
'Add controls to the PopUp menu
Set oBtn = oPopUp.Controls.Add(msoControlButton)
With oBtn
.Caption = "My Number 1 Macro"
.FaceId = 71
.Style = msoButtonIconAndCaption
'Identify the module and procedure to run
.OnAction = "MySCMacros.RunMyFavMacro"
End With
Set oBtn = Nothing
'Add a Builtin command using ID 1589 (Co&mments)
Set oBtn = oPopUp.Controls.Add(msoControlButton,1589)
Set oBtn = Nothing
'Add the third button
Set oBtn = oPopUp.Controls.Add(msoControlButton)
With oBtn
.Caption = "AutoText Complete"
.FaceId = 940
.Style = msoButtonIconAndCaption
.OnAction = "MySCMacros.MyInsertAutoText"
End With
Set oBtn = Nothing
Add_Individual:
'Or add individual commands directly to menu
Set oBtn = CommandBars.FindControl(Tag:="custCmdBtn")
If Not oBtn Is Nothing Then Exit Sub
'Add control using built-in ID 758 (Boo&kmarks...)
Set oBtn = Application.CommandBars("Text").Controls.Add(msoControlButton,758,2)
oBtn.Tag = "custCmdBtn"
If MsgBox("This action caused a change to your Add-In template." _
& vbCr + vbCr & "Recommend you save those changes now.",vbInformation + vbOKCancel,_
"Save Changes") = vbOK Then
ThisDocument.Save
End If
Set oPopUp = Nothing
Set oBtn = Nothing
lbl_Exit:
Exit Sub
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。