Reputation: 78
I am trying to insert a custom field (ProtocolNumber), created under Document Properties in Word, into a table cell with additional text around it. I'm not quite sure how to use the Fields.Add function in this case. Sorry if question is too basic, but I'm a total hacker in VBA.
NoOfCol = 5
Set tblNew = ActiveDocument.Tables.Add(Selection.Range, 9, NoOfCol,
wdAutoFitWindow)
With tblNew
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
.Columns(1).PreferredWidth = 100 * NoOfCol * 3 / (NoOfCol + 1)
End With
tblNew.Borders.InsideLineStyle = wdLineStyleSingle
tblNew.Borders.OutsideLineStyle = wdLineStyleSingle
tblNew.Cell(Row:=1, Column:=1).Merge _
MergeTo:=tblNew.Cell(Row:=1, Column:=NoOfCol)
tblNew.Cell(1, 1).Split NumColumns:=2
tblNew.Cell(1, 1).Range.Text = "PROTOCOL: [ProtocolNumber]" & vbCrLf & "DRUG/INDICATION:
:
:
Upvotes: 1
Views: 1980
Reputation: 14383
This is the code you might be looking for.
Dim Rng As Range
Dim PropName As String
Set Rng = tblNew,Cell(1, 1).Range
Rng.Collapse wdCollapseStart ' insert field at start of cell
PropName = "Protocol number" ' Custom document property by this name must exist
Rng.Fields.Add Range:=Rng, _
Type:=wdFieldEmpty, _
Text:="DOCPROPERTY """ & PropName & """", _
PreserveFormatting:=True
Note that Word will not be able to access the columns in your table after you do any horizontal merging. Similarly, the ability to access rows will be lost when any cells are merged vertically. In a nutshell, merging cells in a table is not a good idea, and if you absolutely must do it then do it after you are done accessing the cells.
Upvotes: 1