我正在尝试编写一个Word宏,它将来自注册表中当前用户的数据插入到文档中的预定义书签中。我有一个ini文件,它指示每个注册表项的名称是什么,然后将该值导入Word宏中的循环。这工作正常(我认为),但Word宏也需要将数据插入到文档中。如果书签在那里,这样可以正常工作,但如果没有,那么宏似乎无论如何都会插入数据。我不希望这样。我只是希望宏插入数据,如果有一个与名称相对应的书签。我已经做到了,所以每个书签都需要被称为“”Bookmark“& sBookMarkname”。
这是代码..
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
即使注册表只包含三个键,宏也会遍历从文本文件中获取的每个名称,并多次插入最后一个注册表项。
答案 0 :(得分:1)
为什么不在插入名称之前检查书签是否存在?
If ActiveDocument.Bookmarks.Exists(sBookmarkName) Then
... insert using your code
End If