如何在Excel VBA中访问Word公共variables

我正试图自动化Excel VBA所做的所有工作。 我的雇主有一套标准化的模板,其中所有的文件都应该从中生成。 我需要从Excel VBA中填充这些模板之一。 Word模板广泛使用VBA。

这是(一些)我的Excel VBA代码:

Sub GenerateReport() ' (Tables, InputDataObj) ' code generating the WordApp object (works!) WordApp.Documents.Add Template:="Brev.dot" ' Getting user information from Utilities.Userinfo macro in Document Call WordApp.Run("Autoexec") ' generating a public variable Call WordApp.Run("Utilities.UserInfo") ' more code End sub 

在Word VBA Autoexec模块中,定义并声明一个名为user的公共variables。 Utilities模块中的user子将填充user 。 这两个例程都运行没有VBA的任何投诉。 然后,我想能够访问我的Excel VBA中的uservariables,但我得到以下错误

编译错误:variables尚未在此上下文中创build。

如何在Excel VBA中访问Word VBAvariables? 我以为这个或多或less是一样的?

编辑: uservariables是用户定义只有String属性的Type 。 复制Word填充uservariables的VBA函数是绝对可行的,只是比我更多的工作,虽然是必要的…

在Word模块中:

 Public Function GetUserVariable() As String '// or whatever data type GetUserVariable = user End Function 

在Excel模块中:

 myUser = WordApp.Run("GetUserVariable") 

或者,您可能能够复制variables值 – 因为它被称为user我怀疑它正在返回有关文档的用户或作者的一些信息。 在这种情况下,您可能会遇到以下情况之一:

 '// Username assigned to the application MsgBox WordApp.UserName '// Username defined by the system MsgBox Environ$("USERNAME") '// Name of the author of the file specified MsgBox CreateObject("Shell.Application").Namespace("C:\Users\Documents").GetDetailsOf("MyDocument.doc", 9) 

另一种select – 如果你只能添加一行代码到Utilities.UserInfo子(在设置你的公共variables之后):

 ActiveDocument.Variables("var_user") = user 

然后,您可以在Excel中轻松访问它:

 Sub GenerateReport() ' (Tables, InputDataObj) ' code generating the WordApp object (works!) 'I am assuming your WordApp object is public, as you don't declare it. 'Capture the new document object Dim newdoc as Object set newdoc = WordApp.Documents.Add(Template:="Brev.dot") ' Getting user information from Utilities.Userinfo macro in Document Call WordApp.Run("Autoexec") ' generating a public variable Call WordApp.Run("Utilities.UserInfo") 'Get and show the value of "user" Dim user as String user = newdoc.Variables("var_user") msgbox, user End Sub 

这是假设user是一个string。

编辑:因为这是一个需要只在Excel VBA上工作,所以我会定义尝试由Scott和MacroManbuild议的方法 – 如果可能的话,在Excel中复制Wordmacros的相同function。

我认为你已经排除了使用原始模板的编辑副本的可能性,在公用文件夹中设置…

为了完整性,还有另一种可能性:实际上可以通过“蛮力”在没有VBProject对象模型的Word文档中注入VBA代码。 如果您将Word文档重命名为.zip文件并将其打开,则会注意到其中包含\word\vbaProject.bin文件。 该文件包含文档的VBA项目,原则上可以通过修改或replace来添加或更改VBA代码。

我做了一些testing,将代码从一个文档移植到另一个文档,只需复制vbaProject.bin文件即可。 如果您有兴趣了解有关此文件的更多信息,可以使用此主题 。

不过要注意的是,用这种技术来做你想做的事情会有点复杂(对于初学者来说,它会涉及到更新Excel VBA中的zip文件),并且需要大量的实验来减less意外地破坏你的风险文件。 如果你正在寻找一个简单而简单的解决scheme,绝对不推荐 – 但这是可能的。