在用vba操作word文档的内容时,经常会遇到需要定位到word文档的末尾或者开头的时候。
如果要在word文档的末尾操作,可以使用如下代码
Sub QQ1722187970()
Dim oDoc As Document
Set oDoc = Word.ActiveDocument
Dim oRng As Range
With oDoc
'oDoc.Content表示整个word文档
Set oRng = oDoc.Content
'oRng.InsertAfter将在文档末尾插入字符
oRng.InsertAfter "asdf"
'oRng.InsertParagraphAfter将在文档末尾插入一个段落
oRng.InsertParagraphAfter
End With
End Sub
如果要在word文档的开头操作,可以使用如下的代码
Sub QQ1722187970()
Dim oDoc As Document
Set oDoc = Word.ActiveDocument
Dim oRng As Range
With oDoc
'oDoc.Range(0, 0)表示文档的开头
Set oRng = oDoc.Range(0, 0)
'oRng.InsertBefore将在文档开头插入字符
oRng.InsertBefore "asdfasdf"
'oRng.InsertParagraphBefore将在文档开头插入一个段落
oRng.InsertParagraphBefore
End With
End Sub


发表评论