我正在使用VBA从excel生成word文档。我有一个for循环,我想添加一个[1行,1列,有边界]表。这是用户可以将他们的评论放在word文档中的区域。当我尝试添加.table.add时,我遇到了不同的错误,包括对象错误。这就是我到目前为止所做的:
Sub GenDocumentables()
Worksheets("checklist").Activate
Dim wdApp As Word.Application
Set wdApp = New Word.Application
Dim saveName As String
Dim NumberOfCells As Integer
With wdApp
.Visible = True
.Activate
'Debug.Print .Version
.Documents.Add
With .Selection
.InsertBreak Type:=wdPageBreak
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.BoldRun
.Font.Size = 13
.TypeText "Documentable Items for "
.TypeText Range("d4").Value
.BoldRun
.TypeParagraph
End With
NumberOfCells = Range("a4", Range("a3").End(xlDown)).Count
For loopcounter = 1 To 2 ' NumberOfCells
With .Selection
.Font.Bold = False
.Style = wdStyleHeading3
.TypeText Range("a3").Offset(loopcounter, 0).Value & " - "
.TypeText Range("a3").Offset(loopcounter, 4).Value
.TypeParagraph
.Font.Size = 10
.TypeText Range("a3").Offset(loopcounter, 5).Value
.TypeParagraph
.Font.Italic = True
.TypeText "<<Please enter your commentary here. Ensure all aspects of the check content are met>>"
.TypeParagraph
'-------------------ADD TABLE HERE-------------------
End With
Next
Set myRange = ActiveDocument.Range(0, 0)
ActiveDocument.TablesOfContents.Add Range:=myRange, UseFields:=False, UseHeadingStyles:=True, LowerHeadingLevel:=3, UpperHeadingLevel:=1
With .Selection
.GoTo What:=wdGoToSection, Which:=wdGoToFirst
.InsertBreak Type:=wdPageBreak
End With
saveName = Environ("UserProfile") & "\Desktop\My Word Doc_" & Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx"
.ActiveDocument.SaveAs2 saveName
'.ActiveDocument.Close
'.Quit
End With
MsgBox "done!"
End Sub
答案 0 :(得分:3)
由于Selection没有方法,因此会出现对象错误.Table 要解决这个问题,您需要使用以下行:
Set newTable = wdApp.ActiveDocument.Tables.Add(SomeRange,1,1)
Tables是Document的成员,您可以使用wdApp.ActiveDocument部分检索它。 在这里,需要定义SomeRange才能使其正常工作。
要尝试运行此代码,请尝试添加一些变量以使其更容易。 返回声明其他变量的位置添加以下内容:
Dim myRange As Word.Range
Dim wdDoc As Word.Document
Dim newTable As Word.Table
在您进入循环之前,在创建文档后添加:
Set wdDoc = wdApp.ActiveDocument
接下来,在你的循环内部,但在你的End With(.Selection)之后你可以添加:
Set myRange = wdDoc.Range(wdDoc.Content.End - 1, wdDoc.Content.End)
Set newTable = wdDoc.Tables.Add(myRange, 1, 1)
newTable.Cell(1, 1).Range.Text = "Hello"
Set myRange = wdDoc.Range(wdDoc.Content.End - 1, wdDoc.Content.End)
myRange.Select
让我们来看看它的作用。
希望这有帮助。