Reputation: 491
I'm trying to dynamically generate a word document from an excel spreadsheet. The way that I am going about doing it now is basically manually finding character count, and then will eventually insert a given item at that specific character count. The given item is stored in excel. So it would be like:
Spreadsheet
| 1 | 2 | 3
Char | 50 | 125 | 250
Item | Hello | Darkness | Friend
And then in the word VBA, use
Dim myCheck As ContentControl
Dim myRange As Range
Dim rng As Long
rng = ''whatever char is for that column
Set myRange = ActiveDocument.Range(start:=rng, End:=rng)
Set myCheck = ActiveDocument.ContentControls.Add(wdContentControlCheckBox, myRange)
'what I am doing now is adding a check box dynamically at a given position on the range. This can be either checkboxes that are added or text or whatever.
The issue is: how do I find locate a specific point on the a word document? The form that I am trying to insert these into is static, so I can safely assume that if I want to insert it at character 100, each time I make a new form it will insert it in the same place.
I tried using 'word count' character button, but that didn't seem to be accurate. It was consistently 40 or so characters in front of where I wanted it to be. Didn't see a pattern.
Is there an easy way to place my cursor at a location on a document and know how many characters came before it, as counted by the range object? Or is there a more efficient way of locating things on a word document, provided that I cannot alter the word document itself in appearance (can't add grids, grid layouts, tables, or anything like that).
Upvotes: 1
Views: 1483
Reputation: 744
I believe the bookmark functionality is what you're looking for.
You can create bookmarks in a static Word Document beforehand and use them as your insertion target... or you can create the bookmarks programmatically with VBA and then use the insert text option.
Examples for using a bookmark to insert text.
Sub InsertAtBookmarkI()
ActiveDocument.Bookmarks("bmAtBookmark").Range.InsertAfter "Some text here"
End Sub
MSDN Document for creating bookmarks programmatically.
Sub Mark()
ActiveDocument.Bookmarks.Add Name:="mark"
End Sub
Sub ThirdPara()
Dim myDoc As Document
' To best illustrate this example,
' Letter.doc must be opened, not active,
' and contain more than 3 paragraphs.
Set myDoc = Documents("Letter.doc")
myDoc.Bookmarks.Add Name:="third_para", _
Range:=myDoc.Paragraphs(3).Range
myDoc.ActiveWindow.View.ShowBookmarks = True
End Sub
Upvotes: 2