Re: Excel VBA to cycle through Word bookmarks and insert ranges (text, graphs & table
Hello Richard.
I know that Excel can grab all Named Ranges. So I have around 10 tables that need copying from Excel to word and around 10 charts that need copying too. Added to that there are probably around 10 text strings that need copying. Ideally I could do it by loading the list of bookmarks from Word:
With wdDoc ReDim sbkmk(1 To .Bookmarks.Count)
'populates array (a list) with bookmark names
For tmp1 = 1 To .Bookmarks.Count
sbkmk(tmp1) = .Bookmarks(tmp1).Name
Next
So now I have the list of bookmarks in the word document where I would like to insert various bits of text, tables or graphs from my Excel document. If the bookmark has the same name as a named range I should be able to match these.
I know that I can load the text in a String as the code by Mr. Plow does this. I was wondering if there is a way that I can load an excel chart into something like a string or a variable, hold it in memory and then dump it into where the word document bookmark is.
I know what format each Bookmark is going to be in so I could create a list something like this:
'Insert all text items
For "ARText1", "ARText2", "ARText3" etc.
Use Function "Insert Text"
'Insert all chart items
For "ARChart1", "ARChart2", "ArChart3" etc.
Use Function "Insert Chart"
'insert all tables
For "ARTable1", "ARTable2", "ArTable3" etc.
Use Function "Insert Table"
(This is obviously not real code)
Mr Plow uses the following Function to insert text, so we have this covered:
Sub FillBookmark(ByRef wdDoc As Object, ByVal vValue As Variant, ByVal sBmName As String, Optional sFormat As String) Dim wdRng As Object
'store the bookmarks range
Set wdRng = wdDoc.Bookmarks(sBmName).Range
'if the optional format wasn’t supplied
If Len(sFormat) = 0 Then
'replace the bookmark text
wdRng.Text = vValue
Else
'replace the bookmark text with formatted text
wdRng.Text = Format(vValue, sFormat)
End If
're-add the bookmark because earlier process destroyed it
wdRng.Bookmarks.Add sBmName, wdRng
End Sub
Display More
The important part of this function is that it re-adds the bookmark allowing the user to update the word document at a future point in time. So the bookmark needs to cover the entire word, chart or table when updating.
The biggest problem I have with Mr Plow's code is the following item:
strValue = Trim(Application.Range(strName).Text)
I am unsure of how one could modify this code to work with charts or tables, or whether that is even possible or not.