如果已經有範圍對象,添加書籤非常簡單。
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