从 VSTO 调用的单词宏



我试图弄清楚为什么我不能运行从用 VB 编写的 VSTO 加载项调用的 Microsoft Word 宏。我能找到的每个参考资料都说你可以用一行话来做到这一点:

Application.Run("MacroName")

宏本身非常简单...它只是切换"键入时替换文本"设置(自动更正.替换文本 = 不是自动更正.替换文本(。当从 Word 本身调用时,这将完美运行。宏链接到 normal.dotm 模板,因此只要打开 Word,它就可用。我正在使用 Word 功能区上的一个按钮,该按钮回调到反过来调用宏的函数。

Public Function DisplayHelp(ByVal control As Office.IRibbonControl)
'On Error Resume Next
Dim wdApp As New Microsoft.Office.Interop.Word.Application        
wdApp.Run("AC_Test")
UpdateLabel()
End Function

单击该按钮不会更改替换文本设置的状态。我在加载项开发方面有些缺乏经验,因此感谢您的任何建议。

谢谢

在 VSTO 外接程序中,不应启动新的 Word.Application。宏调用正在您看不到的这个新的 Word 实例中运行。它未在运行 VSTO 外接程序的应用程序实例中运行,你单击了该按钮。

(此外,按原样启动 Word 的新实例可能会使 winword 的"孤立"实例.exe运行,这些实例未被清理(内存泄漏(,因为您没有处理/释放对象。

为了从VSTO加载项中寻址Word.Application,请使用Globals.ThisAddin.Application。因此,例如:

Word.Application wdApp = Globals.ThisAddin.Application
wdApp.Run("AC_Test")

有关 MSDN 的文档资料中的参考:对 Office 项目和程序 VSTO 外接程序中对象的全局访问

请注意,有时 Word 不清楚宏的位置。在这种情况下,您可能需要包含宏的模块名称,甚至是包含宏的 dotm 的完整路径。但是,这不太可能是Normal.dotm的问题...

确保在默认 VBA 模块中声明了 VBA 子。您可以在 VBA 和 Visual Studio Office Solutions (VSTO( 之间的互操作一文中阅读有关此内容的详细信息。

有时还有助于指定所有参数显式传递默认值的Type.Missing。例如:

Application.Run("Test",
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

请注意,您的 VBA 子应声明为公共。

有关详细信息,请参阅应用程序.运行。

也许有人会发现在 ms project 中创建和调用宏很有用 (2016(

添加到引用 Microsoft.Vbe.Interop 并使用

using VBIDE = Microsoft.Vbe.Interop;

链接到项目

public Microsoft.Office.Interop.MSProject.Application app = new Microsoft.Office.Interop.MSProject.Application();

克里特宏

private void button1_Click(object sender, RibbonControlEventArgs e)
{
StringBuilder sb;
sb = new StringBuilder();
sb.Append("Sub aaa()"+"n");
sb.Append("Message "m1" " + "n");
sb.Append("End Sub"+"n");
VBIDE.VBComponent oModule;
oModule = app.Application.ActiveProject.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
oModule.Name = "PMP1";
oModule.CodeModule.AddFromString(sb.ToString());
sb.Clear();
sb.Append("Sub aaa2(ByVal word)" + "n");
sb.Append("Message word " + "n");
sb.Append("End Sub" + "n");
sb.Append("n");
sb.Append("Sub aaa3(ByVal word)" + "n");
sb.Append("Message word " + "n");
sb.Append("End Sub" + "n");
oModule = app.Application.ActiveProject.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
oModule.Name = "PMP2";
oModule.CodeModule.AddFromString(sb.ToString());
}

调用宏

app.Application.Run("aaa3", "test");

最新更新