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

StackOverflow https://stackoverflow.com/questions/11333817

  •  19-06-2021
  •  | 
  •  

Pregunta

Picture of the document

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top