如果已经有范围对象,添加书签非常简单。
ActiveDocument.Bookmarks.Add Name:=rngBookmark.Text, Range:=rngBookmark
获取范围往往是一项艰巨的任务。 现在你说这些是节标题。他们是真正的字节标题?他们是否以某种风格划定界限?它们在文档的正文中还是在页眉中?
您可以像这样循环浏览文档的各个部分,并将范围设置为该部分的开头。
Dim sectCurrent As Word.Section
Dim rngCurrent As Word.Range
For Each sectCurrent In ActiveDocument.Content.Sections
' get range that refers to the whole section
Set rngCurrent = sectCurrent.Range.Duplicate
' collapse the range to the start of the section
rngCurrent.Collapse wdCollapseStart
' expand the range to hold the first "word"
' you can also use other units here like wdLine
rngCurrent.MoveEnd Unit:=wdWord, Count:=1
' now that you have the range you can add the bookmark
' you can process the range and create your own name with a custom function GenerateBookmarkName. To get the string, just use rngCurrent.Text.
ActiveDocument.Bookmarks.Add Name:=GenerateBookmarkName(rngCurrent), Range:=rngCurrent
Next sectCurrent
现在,如果他们不实际的部分,你会经常要使用的查找对象通过所有这些物品查找文档和循环的东西。这里的诀窍是知道要搜索什么。下面是一个示例循环。
' setup range object for search results
Set rngFind = ActiveDocument.Content
' cycle through search results looking for whatever
With rngFind.Find
' search text
.Text = "FINDME"
.Format = False
.Wrap = wdFindStop
' loop while find is successfull
Do While .Execute
' get range you can modify based on found item
' each time you call .Execute rngFind is changed to the found text
Set rngModifyMe = rngFind.Duplicate
Loop
End With
更多字VBA帮助,您可以点击这里访问次数字的MVP网站:http://word.mvps.org