I am trying to make a macro in Excel, which takes a sample Word file with some bookmarks on it and writes something on the bookmarks. It works for one bookmark, but for the second, third, etc it simply deletes the other entries.
E.g. after the running of my code, I have only written "Info4". I see Info1, Info2 and Info 3 being written and deleted while the macro is run.
Any ideas? Here comes the code:
Option Explicit
Public Sub Main()
If [set_in_production] Then On Error GoTo Main_Error
Dim word_obj As Object
Dim word_doc As Object
Dim obj As Object
Dim rng_range As Variant
Dim obj_table As Object
Dim origDoc$
Dim l_row&: l_row = 2
On Error Resume Next
Set word_obj = GetObject(, "Word.application.14")
If Err.Number = 429 Then
Set word_obj = CreateObject("Word.application.14")
Err.Number = 0
End If
If [set_in_production] Then On Error GoTo Main_Error Else On Error GoTo 0
origDoc$ = ActiveWorkbook.Path & "\" & CStr(Replace(Time, ":", "_")) & "_" & generate_name & ".docx"
word_obj.Visible = True
word_obj.DisplayAlerts = False
Set word_doc = word_obj.Documents.Open(ActiveWorkbook.Path & "\SAMPLE_2.docx")
word_obj.activedocument.SaveAs Filename:=origDoc
'after the saveas -> write
Dim obj_BMRange As Object
Set obj_BMRange = word_obj.activedocument.Bookmarks("Info1").Range
obj_BMRange.Text = "Info1" & vbCrLf
Set obj_BMRange = Nothing
Set obj_BMRange = word_obj.activedocument.Bookmarks("Info2").Range
obj_BMRange.Text = "Info2" & vbCrLf
Set obj_BMRange = Nothing
Set obj_BMRange = word_obj.activedocument.Bookmarks("Info3").Range
obj_BMRange.Text = "Info3" & vbCrLf
Set obj_BMRange = Nothing
Set obj_BMRange = word_obj.activedocument.Bookmarks("Info4").Range
obj_BMRange.Text = "Info4" & vbCrLf
Set obj_BMRange = Nothing
word_obj.DisplayAlerts = False
Set word_obj = Nothing
Set word_doc = Nothing
Set rng_range = Nothing
Set obj = Nothing
Set obj_table = Nothing
On Error GoTo 0
Exit Sub
Main_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Main of Sub mod_main"
End Sub
I have tried to rewrite the bookmarks, once they are deleted, but the success was no different. Thus, waiting for ideas! :D
obj_BMRange
and setword_obj.activedocument.Bookmarks("Info2").Range.Text
directly? – arcadeprecinctobj_BMRange.Text =
, what happens if you useobj_BMRange.InsertAfter "Info2" & vbCrLf
– LocEngineer