使用VBA在Access中创建Word文档中的表

梅泽克

我正在尝试从Access数据库在Word文档模板中创建表。

这部分代码可以从Word本身正常运行,并根据需要创建表。我想知道是否有可能从Access运行此代码并指向要在其中创建表的特定Word文档。

Dim numberOfTables As Integer
Dim iCount As Integer

numberOfTables = InputBox("How many tables to make?", "Tables")

For iCount = 0 To numberOfTables - 1

    ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:= _
        3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        '.ApplyStyleRowBands = True 'Office 2010
        '.ApplyStyleColumnBands = False 'Office 2007
    End With

    Selection.EndKey Unit:=wdStory
    Selection.TypeParagraph

Next iCount
ib11

您需要做的是首先从Access中打开Word的新实例。这是通过以下命令完成的:

Set wrdApp = CreateObject("Word.Application")

然后要使其可见并添加文档,请从那时起使用该对象:

wrdApp.Visible = True
Set myDoc = wrdApp.Documents.Add   'Here you should also keep the new document as an object so you can directly refer to it

或者,如果您使用模板,则需要打开它:

wrdApp.Visible = True
Set myDoc = wrdApp.Documents.Open ("C:\database\template.docx")

然后是您需要对上面的代码进行相应修改的代码:

For iCount = 0 To numberOfTables - 1

    myDoc.Tables.Add Range:=Selection.Range, NumRows:=2, NumColumns:= _
        3, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
    With myDoc.ActiveWindow.Selection.Tables(1)  
'Note here that for the Selection object you need to refer to the active window
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        '.ApplyStyleRowBands = True 'Office 2010
        '.ApplyStyleColumnBands = False 'Office 2007
    End With

    myDoc.ActiveWindow.Selection.EndKey Unit:=wdStory
    myDoc.ActiveWindow.Selection.TypeParagraph

Next iCount

这应该可以帮助您入门。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章