VBA Interop:有没有办法在 word 宏中显式使用 Excel 数据类型,反之亦然?

VBA Interop: Is there a way to Explicitly use Excel data types in a word macro and vise versa?

我正在使用 Word 宏从 excel 电子表格中读取数据,因此我可以使用该电子表格从模板中实例化文档,并在 excel [中的实例化文档中设置属性=28=]。我试图尽可能明确地使用类型,但事实证明,从 excel 选择返回的对象的行类型与 word 文档中的行类型不同。现在我想起来其实并不那么令人惊讶。 excel 电子表格行类型和单词 table 行类型之间是否存在比 Object 更具体的公共基础 class?也许是一种指定 excel 行类型的方法?或者是我最好的选择是使用 Object 类型而不用担心细节。动态类型在这里很神奇,大多数 class 方法都是相同的。

我也对来自 excel VBA 的 运行 基于单词的 VBA 子程序(位于 normal 中)感兴趣。我试图通过 Google 查找它,但没有任何运气。

胆子来了:

 Set testList = LoadExcel(strFile)
 testList.Activate

 Dim allSuites As Object 
 ' LoadExcel also selects the rows that contains the data we want in excel
 Set allSuites = testList.sheets("FullSuiteList").Application.Selection

 Dim myRow As row
 Dim Columns() As String

    Dim i As Integer

    ' Previously I used a table in word, but there are too many columns 
    '     to be manageable
    ' LoadPropertyNames testList.Tables(1).Rows(1), Columns
    ' For i = 2 To testList.Tables(1).Rows.Count


    ' Now we get data directly from our Excel sheet 
    LoadPropertyNames allSuites.Rows(1), Columns

    For i = 2 To allSuites.Rows.Count
        CreateOne allSuites.Rows(i), Columns
   Next I

   ' row type yields type mismatch at runtime.  myrow as Object works though.
   Function LoadPropertyNames(myRow As row, Columns() As String) 
   ...
   End Function

   ' row type yields type mismatch at runtime.  myrow as Object works though.
   Function CreateOne(myRow As row, Columns() As String)        
   ...
   End Function

在 VBA 编辑器的“工具”菜单中选择“引用”,然后将 "Microsoft Excel ##.# Object Library" 添加到您的 Word VBA 项目中。这将使您能够访问 Excel 的所有对象。请注意,一些对象名称,例如"Range" 与 Excel 在 Word 中代表不同的对象,因此根据需要将变量声明为 Word.Range 或 Excel.Range。

在有关 运行Normal 模板子例程之一的评论中回答您的问题。首先在 Excel 中添加对 Word 对象模型的引用 --- 在“工具”菜单中选择“引用”,然后将 "Microsoft Word ##.# Object Library" 添加到您的 Excel 项目中。那么下面是一个如何调用 Normal 模板 sub 的例子:

Sub RunNormalTemplateSub()
    Dim wdapp As Word.Application
    Dim wddoc As Word.Document

    Set wdapp = New Word.Application
    wdapp.Visible = True

    ' This is the line that runs the sub
    ' This runs a sub named "ThisIsATest"
    ' in the module "Sandbox"
    ' in the Project/Template "Normal"
    wdapp.Run "Normal.Sandbox.ThisIsATest"

    ' If the sub takes arguments then you would call
    ' wdapp.Run "Normal.Sandbox.ThisIsATest", Arg1, Arg2


    Set wdapp = Nothing

End Sub

注意 Word 是 运行ning 子例程。我不知道有什么方法可以让 Excel 运行 Word 子程序(也许可以,但我不知道怎么做)。

希望对您有所帮助