[英]Create table in Word Document From Access using VBA
我正在尝试从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
您需要做的是首先从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
这应该使您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.