2009-06-03 62 views
1

我試圖編寫一個Word宏,它將當前用戶在註冊表中的數據插入到文檔中的預定義書籤中。我有一個ini文件,它指定每個註冊表項的名稱,然後將該值導入到Word宏中的循環中。這工作正常(我認爲),但Word宏也需要將數據插入到文檔中。如果書籤存在,這可以正常工作,但如果它們不存在,宏就會插入數據。我不想那樣。我只想讓宏插入數據,如果有書籤與此名稱相關。我已經做到這樣,每個書籤都需要被稱爲「」Bookmark「& sBookMarkname」。Word VBA宏中的錯誤,試圖將值插入到書籤中

而這裏的代碼..

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 

現在,錯誤發生在大約這裏:

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

sBookMarkName = "" 
sBookMarkName = (sBookMarkNametemp) 

If sVerdi <> Felter Then 

即使註冊表中只包含三個按鍵,宏經歷從得到每名該文本文件並多次插入最後一個註冊表項。

回答

1

爲什麼不在插入名稱之前檢查書籤是否存在?

If ActiveDocument.Bookmarks.Exists(sBookmarkName) Then 
    ... insert using your code 
End If 
+0

親愛的上帝......非常感謝你! :)我只是一個白癡:) – 2009-06-03 07:48:57