Hi, I writed a code that should delete the bookmarks in a wordfile selected by the user. I run the macro but in the end the bookmarks are not being deleted.
VBA Code:
Option Explicit
Dim wdApp As Object
Dim wdDoc As Object
Dim wdAppCreated As Boolean
Private Sub Add_Click()
Dim selectedItem As String
' Check if an item is selected in ListBox1
If Me.ListBox1.ListIndex <> -1 Then
selectedItem = Me.ListBox1.List(Me.ListBox1.ListIndex)
' Add the selected item to ListBox2
Me.ListBox2.AddItem selectedItem
' Remove the selected item from ListBox1
Me.ListBox1.RemoveItem Me.ListBox1.ListIndex
End If
End Sub
Private Sub Undo_Click()
Dim selectedItem As String
' Check if an item is selected in ListBox2
If Me.ListBox2.ListIndex <> -1 Then
selectedItem = Me.ListBox2.List(Me.ListBox2.ListIndex)
' Add the selected item to ListBox1
Me.ListBox1.AddItem selectedItem
' Remove the selected item from ListBox2
Me.ListBox2.RemoveItem Me.ListBox2.ListIndex
End If
End Sub
Private Sub Cancel_Click()
'Close the Userform
Unload Me
End Sub
Private Sub Finish_Click()
Dim bookmarkName As String
Dim bm As Object
Dim i As Long
On Error GoTo ErrorHandler
' Loop through each item in ListBox1 and replace the empty spaces with underscores in the bookmark name
For i = 0 To Me.ListBox1.ListCount - 1
bookmarkName = Replace(Me.ListBox1.List(i), " ", "_")
If wdDoc.Bookmarks.Exists(bookmarkName) Then
MsgBox "Deleting bookmark: " & bookmarkName ' display the name of the bookmark being deleted
wdDoc.Bookmarks(bookmarkName).Delete
End If
Next i
On Error GoTo 0
' Save and close the Word document
wdDoc.Save
wdDoc.Close
' Close the Word application
wdApp.Quit
' Close the Userform
Unload Me
Call ReplaceWordsBetweenAngleBrackets
Exit Sub
ErrorHandler:
MsgBox "An error has occurred: " & Err.Description
End Sub
Private Sub UserForm_Initialize()
Dim bm As Object
On Error GoTo ErrorHandler
' Try to get an existing instance of Word, or create a new instance if none is found
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo ErrorHandler
' Open the specified Word document
Set wdDoc = wdApp.Documents.Open("C:\Temp.print\wordTemplate.docx")
' Populate the ListBox with the bookmarks
For Each bm In wdDoc.Bookmarks
If Left(bm.Name, 4) <> "logo" And Left(bm.Name, 6) <> "footer" Then
Me.ListBox1.AddItem Replace(bm.Name, "_", " ")
End If
Next bm
' Set a flag indicating whether the Word application was created in this routine
wdAppCreated = (Err.Number <> 0)
Exit Sub
ErrorHandler:
MsgBox "An error has occurred: " & Err.Description
End Sub