[英]Excel VBA null embedded word document bookmarks before inserting text
[英]Write text and bookmarks to a Word template embedded in a workbook
(此问题是有关如何使用 Word应用程序界面(而不是就地)中嵌入Excel工作簿中的文档的后续操作。之所以这样做,是因为能够将结果另存为独立文档。)
此代码正在执行所需的操作。 打开嵌入式Word模板,填写并保存为新副本。 唯一不起作用的部分是.Application.Quit False
。 收到Word错误:“ Microsoft Word停止工作”。 失败的可能原因是什么?
Sub opentemplateWord()
Dim sh As Shape
Dim objOLE As OLEObject
Dim objWord As Object 'Word.Document
Dim objRng As Object 'Word.Range
Dim objUndo As Object 'Word.UndoRecord
Dim cell As Excel.Range
Dim xlRng As Excel.Range
Dim xlSht As Worksheet
Set xlSht = Sheets("Main")
With xlSht
Set xlRng = .Range("E1", .Range("E" & Rows.Count).End(xlUp))
End With
''The shape holding the object from 'Create from file'
''Object 2 is the name of the shape
Set sh = Worksheets("Templates").Shapes("WordFile")
''Activate the contents of the object
sh.OLEFormat.Activate
Set objOLE = sh.OLEFormat.Object
Set objWord = objOLE.Object
With objWord
Set objRng = .Range.Characters.Last
Set objUndo = .Application.UndoRecord
objUndo.StartCustomRecord ("Doc Data")
Set xlSht = Sheets("Main")
.Bookmarks("ProjectName1").Range.Text = xlSht.Range("B10").Value
.Bookmarks("ProjectName2").Range.Text = xlSht.Range("B11").Value
.Bookmarks("ProjectName3").Range.Text = xlSht.Range("B12").Value
.Bookmarks("ProjectName4").Range.Text = xlSht.Range("B13").Value
.Bookmarks("ProjectName5").Range.Text = xlSht.Range("B14").Value
For Each cell In xlRng
objRng.InsertAfter vbCr & cell.Offset(0, -1).Text
Select Case LCase(cell.Value)
Case "title"
objRng.Paragraphs.Last.Style = .Styles("Heading 1")
Case "main"
objRng.Paragraphs.Last.Style = .Styles("Heading 2")
Case "sub"
objRng.Paragraphs.Last.Style = .Styles("Heading 3")
Case "sub-sub"
objRng.Paragraphs.Last.Style = .Styles("Heading 4")
Case "par"
objRng.Paragraphs.Last.Style = .Styles("Normal")
End Select
Next cell
Set xlSht = Sheets("Main")
.SaveAs2 ActiveWorkbook.Path & "\" & _
xlSht.Range("B2").Value & ", " & _
xlSht.Range("B3").Value & "_" & _
xlSht.Range("B4").Value & "_" & _
xlSht.Range("B5").Value & ".docx"
objUndo.EndCustomRecord
.Undo
.Application.Quit False '<---- Please close Word application
End With
Set objWord = Nothing '<---- Please free up objWord
End Sub
自动化时,由于各种原因,另一个Office应用程序内存可能会“阻塞”。 一个重要因素是管理代码已使用的对象 。 在某些时候,需要释放这些内存以释放内存。 如果未正确处理它们,则它们可以使应用程序保持打开状态(即使看不见)也可能会引起问题。
一个可能的问题可能是 xlSheet
的多重实例化。 由于它总是被分配相同的工作表,因此只需要执行一次。 如果要重新使用一个对象(用于另一个对象),并且代码有问题,请先将该对象设置为Nothing
然后再为其分配其他对象。 (这通常不是必需的,但有时会有所帮助。)
问题中的代码在Excel中运行,并使用许多Word对象。 这些Word对象可能会成为问题(过程结束时,Excel对象将“超出范围”)。 因此,这是很好的编码习惯这样设置的对象Nothing
,只要他们不再需要。
问题中的示例代码来说明:
With objWord 'a Word document
objUndo.EndCustomRecord
.Undo
Set objUndo = Nothing '<---- Release Word objects in Excel code
Set objRng = Nothing
.Application.Quit False '<---- Please close Word application
End With
Set objWord = Nothing '<---- Please free up objWord
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.