问题
I need to generate bookmarks in Word 2010 programmatically, with the header name as the bookmark name.
I have the following code which makes a word a bookmark, but the bookmark name remains the same as the string Heading 1
is only available in the name variable:
Sub bookmarking()
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:=" Heading 1"
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
End Sub
Instead of the Heading 1
in the name variable, I want content from the clipboard. Please help me replace that Heading 1
with clipboard content.
回答1:
Use a DataObject
from the Microsoft Forms 2.0 Object Library
:
Private Function GetClipboardData()
Dim objDataObject As MSForms.DataObject ''need to add reference in Tools |References
Set objDataObject = New MSForms.DataObject
objDataObject.GetFromClipboard
On Error Resume Next
GetClipboardData = objDataObject.GetText
If Err.Number = -2147221404 Then
MsgBox "Error: current clipboard data is either empty or is not text. Clibpoard must contain text."
End If
End Function
Then, back your main code, have the bookmark name be this clipboard data:
...
.Add Range:=Selection.Range, Name:=GetClipboardData()
...
Is this a good start for you? There are other ways which may be more robust depending on your needs. However this should serve as good proof-of-concept.
来源:https://stackoverflow.com/questions/11333817/generate-bookmarks-in-word-2010-programmatically-with-the-header-name-as-the-bo