我正在尝试从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
答案 0 :(得分:2)
您需要做的是首先从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
这应该让你开始。