Generate bookmarks in Word 2010 programmatically, with the header name as the bookmark name

北慕城南 提交于 2019-12-23 01:42:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!