Create table in Word Document From Access using VBA

泪湿孤枕 提交于 2021-02-11 03:35:34

问题


I am trying to create tables in a Word document template from my Access database.

This bit of code runs fine from Word itself and creates tables as required. I was wondering if its possible to run this code from Access and point to a specific word document in which to create the tables.

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

回答1:


What you need to do is to first open a new instance of Word from Access. This is done by the following command:

Set wrdApp = CreateObject("Word.Application")

Then to make it visible and to add a document, you use this object from that point on:

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

Or if you use a template you need to open it instead:

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

And then comes your code that you need to modify accordingly to the above:

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

This should get you started.



来源:https://stackoverflow.com/questions/37006698/create-table-in-word-document-from-access-using-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!