Using word vba to format parts of table cell text

瘦欲@ 提交于 2020-07-11 03:36:14

问题


I'm using the following code to combine text from two excel cells into a word table cell. I want to format the first part (captionStr) as bold but can't seem to figure out how to specify just that part of the range.

I tried .Range(0,Len(captionStr)).Font.Bold=True and .Range.Characters(0,Len(captionStr)).Font.Bold=True but both give me "wrong number of argument" errors. I'm using Office 2010 with MS Word 14.0 Object Reference

With tbl.Cell(nRow, 2).Range
    .Style = rfpDoc.Styles(wdStyleNormal)
    captionStr = CStr(nSection) + ". " + ActiveCell.Text
    bodyStr = ActiveCell.Offset(0, 1).Text
    .Text = captionStr
    .Range.InsertParagraphAfter
    .Range.InsertAfter(bodyStr)
End With

回答1:


The trick is to use a Range object, rather than refer to the entire cell Range when writing the information. This gives you finer control over formatting, as you go. The formatting will always apply to the current content of the Range. So more like

Dim rngCell as Word.Range
Set rngCell = tbl.Cell(nRow, 2).Range
With rngCell
  'Go into the cell, rather than the entire cell
  .Collapse wdCollapseStart
  'other stuff
  .Text = captionStr & vbCr
  .Font.Bold = True
  'Move to the end of the range
  .Collapse wdCollapseEnd
  'Doing this in a table cell moves to the next cell, so one back
  .MoveEnd wdCharacter, -1
  'Now the rest of the content
  .Text = bodyStr
  .Font.Bold = False
End With

Think of a Range like a Selection, and collapsing it like using the left-/right arrow key to "collapse" the selection to a point.



来源:https://stackoverflow.com/questions/36729431/using-word-vba-to-format-parts-of-table-cell-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!