使用 VBA 在 Word Document From Access 中创建表格 [英] Create table in Word Document From Access using VBA
问题描述
我正在尝试在我的 Access 数据库中的 Word 文档模板中创建表格.
I am trying to create tables in a Word document template from my Access database.
这段代码从 Word 本身运行良好,并根据需要创建表格.我想知道是否可以从 Access 运行此代码并指向要在其中创建表格的特定 Word 文档.
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
推荐答案
您需要先从 Access 中打开一个新的 Word 实例.这是通过以下命令完成的:
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
这应该会让你开始.
这篇关于使用 VBA 在 Word Document From Access 中创建表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!