【发布时间】:2014-04-23 14:58:30
【问题描述】:
我正在尝试使用 Access 2007 VBA 在 Word 文档的表格中插入一行。我尝试过 ListRows、Rows、Insert、EntireRow.Insert 等。我找到了 Microsoft 对 2010+ 的帮助,但在 2007 年没有任何帮助。我很确定这是因为我不了解如何执行插入的语法适当地。以下是我的代码,有人可以帮忙吗?我的 Word 文档有 1 个表格,其中 1 行 7 列。谢谢!
Public Sub documentBilletingReserve()
' Create pointers to Word Document
Dim objWord As Word.Application
Dim objDoc As Word.Document 'doc As Word.Document
Dim bolOpenedWord As Boolean
' Get pointer to Word Document
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err.Number = 429 Then
' If Word is not opened, open it
Set objWord = CreateObject("Word.Application")
bolOpenedWord = True
End If
objWord.Visible = True ' Set this to true if you want to see the document open
On Error GoTo 0
'Create New Blank Document
Set objDoc = objWord.Documents.Add("Z:\08_Volume Management\ACCESS\EMAILTEMPLATES\BilletingRequest.dotx")
'Create Excel Table in Word doc to populate request
Dim currentRow As Integer
currentRow = 2
Dim objRange
Dim objTable
Set objRange = objDoc.Range
'objDoc.Tables.Add objRange, intNoOfRows, intNoOfColumns
Set objTable = objDoc.Tables(1)
'objTable.Borders.Enable = False ' Set to true to see the borders
'objTable.Cell(2, 1).Range.Text = "RM"
' Loop through delegates
' Pick Names Delegate Names
Dim finishedSearch As Boolean
Dim counterDelegate As Integer
counterDelegate = 2
finishedSearch = False
MMRank = DLookup("[Rank]", "ModelManagers", "[ID] = " + CStr(counterDelegate))
MMFirstName = DLookup("[FirstName]", "ModelManagers", "[ID] = " + CStr(counterDelegate))
MMLastName = DLookup("[LastName]", "ModelManagers", "[ID] = " + CStr(counterDelegate))
objTable.Cell(2, 1).Range.InsertAfter Text:="RM"
‘************************************************************
‘********** INSERT ROW TO TABLE IN WORD HERE
‘************************************************************
Set rowNew = objTable.ListObject.ListRows.Add(AlwaysInsert:=True)
rowNew.Range.cells(1, 1).Value = MMGender
objTable.Cell(2, 1).Range.Text = CStr(currentRow - 1)
objTable.Cell(2, 3).Range.Text = MMRank
objTable.Cell(2, 4).Range.Text = MMFirstName + " " + MMLastName
currentRow = currentRow + 1
‘************************************************************
' This will shift the focus to Word
'objWord.Activate
'Save New Document
'On Error Resume Next
Dim stringFilename As String
stringFilename = "Z:\08_Volume Management\ACCESS\EMAILATTACHMENTS\BilletingRequest" + [VolumeName] + ".docx"
'On Error Resume Next
objDoc.SaveAs (stringFilename)
'On Error Resume Next
'On Error GoTo 0
'Close and release pointers
objDoc.Close False 'doc.Close False
Set objDoc = Nothing
If bolOpenedWord = True Then
'Close Word
objWord.Quit
End If
Set objWord = Nothing
End Sub
【问题讨论】:
-
Word 是如何做到的?我的意思是打开录制宏,通过 UI 执行您想要的操作并查看 Word 生成的代码。
标签: ms-access vba ms-access-2007