views:

205

answers:

1

Hi! I've got data in the registry under Current User which I want to add into predefined bookmarks in Word documents. Now, the thing is, I want the exact same macro in every single Word document and have the macro skip the step if it can't find the predefined bookmark.

I've got this code already where I need to predefine an array of the total data I've got in the registry. The macro stores the values of each subkey from the registry into a string. But doesn't insert the value into the bookmark unless the bookmark exists. Well, that's the idea anyway.

Public Sub TemplateData()

    Dim objShell
    Dim strShell
    Dim strDataArea
    Dim Values() As String
    Dim Fields

    ' Input the exact same key as in registry
    Fields = Array("DEPARTMENT", "LETTER", "LNAME", "FNAME")


    Set objShell = CreateObject("Wscript.Shell")

    strDataArea = "HKCU\Templates\"
    On Error Resume Next


    For iTeller = 0 To UBound(Fields)

        Dim sBookMarkName, sValue
        sBookMarkName = "Bookmark" & Fields(iTeller)
        sValue = objShell.RegRead(strDataArea & Fields(iTeller))

        Selection.GoTo What:=wdGoToBookmark, Name:=sBookMarkName
        Selection.Delete Unit:=wdCharacter, Count:=0
        Selection.InsertAfter sValue       

    Next
    On Error GoTo 0

End Sub

If I put a breakpoint on the bottom Next, I can see that it indeed finds the bookmarks, but somehow it inserts the values of every registry subkey until it finds the correct one. And the initial idea is also to have the macro delete whatever words are in the bookmkarks if I run the macro again since if the data in the registry get updates, the macro should pick that up and insert it into the document.

Can anyone find what might be wrong here?

+1  A: 

http://stackoverflow.com/questions/943402/vba-word-error-in-macro-trying-to-insert-values-into-bookmarks has answers. Kenny learned himself (re-set the Bookmark):

 ActiveDocument.Bookmarks.Add Range:=Selection.Range, Name:=sBookMarkName

and Tom helped to check before use...

If ActiveDocument.Bookmarks.Exists(sBookmarkName) Then
    ... insert using your code
End If
GeraldStü