Hello.
I'm trying to create a code that the user can eliminate the bookmarks on a word document throught a userform but everytime I click on Finish_Button in order to delete the bookmarks that are listed at listbox2 on the word file and save changes it says object required
I'm trying to create a code that the user can eliminate the bookmarks on a word document throught a userform but everytime I click on Finish_Button in order to delete the bookmarks that are listed at listbox2 on the word file and save changes it says object required
VBA Code:
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
On Error GoTo ErrorHandler
' Loop through each item in ListBox2 and remove the corresponding bookmark from the Word document
For i = 0 To Me.ListBox2.ListCount - 1
bookmarkName = Me.ListBox2.List(i)
If wdDoc.Bookmarks.Exists(bookmarkName) Then
wdDoc.Bookmarks(bookmarkName).Range.Delete
End If
Next i
' Save and close the Word document
wdDoc.Save
wdDoc.Close
' Close the Word application (if it was created in UserForm_Initialize)
If wdAppCreated Then
wdApp.Quit
End If
' Close the Userform
Unload Me
Exit Sub
ErrorHandler:
MsgBox "An error has occurred: " & Err.Description
End Sub
Private Sub UserForm_Initialize()
Dim wdApp As Object
Dim wdDoc As Object
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