views:

792

answers:

2

Hi, I'm trying to write a Word macro which inserts data from the Current User in Registry into predefined bookmarks in the document. I've got an ini-file which dictates what the names of each registry entry is, and that value is then imported into a loop in the Word Macro. This works fine (I think), but the Word macro needs to insert the data into the document as well. And this works fine if the bookmarks are there, but if they aren't, the macro seems to insert data anyway. I don't want that. I just want the macro to insert the data IF there's a bookmark coresponding to the name. I've made it so that each bookmark needs to be called ""Bookmark" & sBookMarkname".

And here's the code..

Sub MalData()
    ''
    ''// MalData Macro
    ''

    Dim objShell
    Dim strShell
    Dim strDataArea
    Dim Verdier() As String
    Dim regPath
    Dim regString
    Dim Felter
    Dim WScript

    Dim sFileName As String
    Dim iFileNum As Integer
    Dim sBuf As String


    sFileName = "C:\felter.ini"
    If Len(Dir$(sFileName)) = 0 Then
        MsgBox ("Can't find " & sFileName)
    End If

    ''//Load values from ini-file which is later used to query the registry

    Set objShell = CreateObject("Wscript.Shell")

    With New Scripting.FileSystemObject
    With .OpenTextFile(sFileName, ForReading)

        If Not .AtEndOfStream Then regPath = .ReadLine
        If Not .AtEndOfStream Then regString = .ReadLine

        Do Until .AtEndOfStream
            Felter = .ReadLine

            On Error Resume Next
            Dim sBookMarkName, sVerdi
            sBookMarkNametemp = "Bookmark" & Felter
            MsgBox (sBookMarkNametemp)
            sVerdi = objShell.RegRead(regPath & "\" & Felter) ''"

            sBookMarkName = ""
            sBookMarkName = (sBookMarkNametemp)

            If sVerdi <> Felter Then
                Selection.GoTo What:=wdGoToBookmark, Name:=sBookMarkName
                Selection.Delete Unit:=wdCharacter, Count:=0
                Selection.InsertAfter sVerdi
                ActiveDocument.Bookmarks.Add Range:=Selection.Range, Name:=sBookMarkName
            End If
        Loop

        On Error GoTo 0
    End With
    End With

End Sub

Now, the error happens at about here:

sVerdi = objShell.RegRead(regPath & "\" & Felter) ''"

sBookMarkName = ""
sBookMarkName = (sBookMarkNametemp)

If sVerdi <> Felter Then

Even if the registry only contains three keys, the macro goes through every name gotten from the text file and inserts the last registry key multiple times.

A: 

Why don't you check if the bookmark exists before inserting the name?

If ActiveDocument.Bookmarks.Exists(sBookmarkName) Then
    ... insert using your code
End If
Tom Juergens
Dear God... Thank you so much! :) I'm just an idiot :)
Kenny Bones
A: 

This code i m trying o run but it's not working for me. Do i need to select any references in the tool menu.