Reputation: 704
my VBA dynamically writes several tables depending on criteria and works quite well.
For example here is adding a row, formatting it and advancing to the next row.
oDoc.Tables(t).Rows.Add 'add a row below control number
oDoc.Tables(t).Rows(i).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
oDoc.Tables(t).Rows(i).Shading.BackgroundPatternColor = oTableHeaderColor
i = i + 1 'advance to row below control number row.
oDoc.Tables(t).Cell(i, 2).Range.Text = "Check Definition"
I do it in this manner because I just don't know how many rows any given table is - so I create the rows as I need them, might be clumsy but it works.
What I need to do is add a check-able checkbox to rows with text like this.
Planned: ☐
I've tried several ways that just don't seem to work. as far as I can tell it's because i'm not creating the table then selecting it. I've tried recording a macro and that just shows the bit about selection first.
Here's what I've got, it pops an error.
oDoc.Tables(t).Cell(i, 2).Range.Text = "Planned: " & oDoc.Tables(t).Cell(i, 1).Range.ContentControls.Add(wdContentControlCheckBox)
I get "requested member of the collection doesn't exist.
If I try to put it on two lines it will just overwrite cell 1. with the checkbox and I can't seem to position it to the end of the cell first. Any ideas? I've tried insertbefore and that works but I have to insert several checkboxes in the same cell.
Any ideas? thank you.
Upvotes: 2
Views: 2125
Reputation: 27634
Getting text + checkbox + other text + second checkbox into one cell is tricky.
This may be one of the few cases, where you actually have to use the Selection
object.
This works for me in Word:
Dim oDoc As Word.Document
Set oDoc = ThisDocument
Const t = 1
Const i = 1
Dim rng As Word.Range
Dim iCheck As Long
Dim sLabel As String
Set rng = oDoc.Tables(t).Cell(i, 2).Range
rng.Select
With Selection
.Collapse Direction:=wdCollapseStart
For iCheck = 1 To 3
sLabel = Choose(iCheck, "Planned: ", " Done: ", " Perhaps: ")
.TypeText Text:=sLabel
.Range.ContentControls.Add wdContentControlCheckBox
' move cursor after checkbox
.MoveRight Unit:=wdCharacter, Count:=2
Next iCheck
End With
In Access, use oWord.Selection
instead (or what you have as reference to Word).
The following works for a single checkbox, but I didn't manage to create a second one after additional text.
Dim rng As Word.Range
Set rng = oDoc.Tables(t).Cell(i, 2).Range
rng.Text = "Planned: "
' set range to end of cell
rng.Collapse Direction:=wdCollapseEnd
' I'm not entirely sure why this is needed, but without the checkbox goes into the next cell
rng.MoveEnd Unit:=wdCharacter, Count:=-1
rng.ContentControls.Add (wdContentControlCheckBox)
Upvotes: 2