Search code examples
excelvbams-wordbookmarks

How do I create a Bookmark after another Bookmark using VBA Excel?


I have a vba code in Excel that computes some calculations. After that I want to get some of the calculations I have obtained to a Word document. in this Word document there is a bullet list like this:

  • XXXXX

Where XXXXX has a bookmark called "ENTERPRISE". I want a code that after opening the Word document using Excel, it creates more bullet points on the list because it depends on the number of enterprises the Excel calculates.

For example, the Excel says there are 3 enterprises. Therefore, the list should look like this:

  • XXXXX
  • XXXXX
  • XXXXX

Where each XXXXX has also a different bookmark in which I'll write the name of each Enterprise on it.

I have the following code for the moment:

    Dim wrdApp As Object, wrdDoc As Object
    Dim strPath As String
    
    strPath = "C:\Users\xxxx.docx"
    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = True
    Set wrdDoc = wrdApp.Documents.Open(Filename:=strPath)
    wrdDoc.Bookmarks("ENTERPRISE").Range.Text = "Enterprise 1"
    wrdDoc.Bookmarks.Item("ENTERPRISE").Range.InsertParagraphAfter 'It inserts a new bullet point but without bookmark

Thank you for your answers and do not hesitate to ask me if you have any questions!


Solution

  • For example: wrdDoc.Bookmarks("ENTERPRISE").Range.Text = "Enterprise 1" & vbCr & "Enterprise 2" & vbCr

    For a loop, you might use something like:

    Dim i As Long, r As Long, StrOut As String
    For i = 1 To n
      With ActiveSheet.Range("A" & r)
        If .Value <> "" Then StrOut = StrOut & vbCr & .Value
      End With
      StrOut = Left(StrOut, Len(StrOut) - 1)
    Next
    wrdDoc.Bookmarks("ENTERPRISE").Range.Text = StrOut