如何引用我刚刚插入的行或表格行

时间:2019-01-26 22:22:46

标签: vba ms-word

我觉得我肯定想念一些明显的东西。我正在使用VBA通过一次向其中写入行来构建Word文档。写完一行后,我需要对其进行格式化-这可以是粗体,设置制表符等。但是,为了格式化一行,我必须能够引用它。所有格式设置工具都在Range或Selection上运行-如何将刚插入的行标识为我要操作的Range? (另外,关于表行的问题是相同的,因为该文档还包含我一次要建立一行的表,因此我需要随时格式化单元格。)

2 个答案:

答案 0 :(得分:1)

这是使用Range对象插入文本并随即设置其格式的方法。最好不要尝试使用SelectionTypeText模拟用户的工作方式。代码运行速度更慢,精确工作也更加困难。只能有一个选择,但是代码可以在许多范围内使用...

要记住的另一个重要点是在创建对象时声明和实例化对象,例如表和表行。

Dim rng1 as Word.Range, rng2 as Word.Range
Set rng1 = ActiveDocument.Content
rng1.Text = "line one" & vbCr
rng1.Font.Bold = True
rng1.Collapse wdCollapseEnd
rng1.Text = "line two" & vbCr
rng1.Font.Bold = False
rng1.Collapse wdCollapseEnd
Set rng2 = rng1.Duplicate
rng2.Text = "line three" & vbCr
rng2.Font.Italic = True
'You can still work with the first range
rng1.ParagraphFormat.Alignment = wdAlignParagraphCenter
'
Dim tbl as Word.Table, rw1 as Word.Row, rw2 as Word.Row
Set tbl = ActiveDocument.Tables.Add
Set rw1 = tbl.Rows(1)
Set r2 = tbl.Rows.Add

答案 1 :(得分:-3)

Sub FormatBold()
Dim StartWord As String, EndWord As String
StartWord = "STARTSTART"
EndWord = "ENDEND"

With ActiveDocument.Content.Duplicate
    .Find.Execute Findtext:=StartWord & "*" & EndWord, MatchWildcards:=True
    .MoveStart wdCharacter, Len(StartWord)
    .MoveEnd wdCharacter, -Len(EndWord)
    .Font.Bold = True ' Or whatever you want to do
End With

End Sub

在编写文本时设置其格式:

Sub StartTyping()

Selection.TypeText Text:="This is the "
Selection.Font.Bold = wdToggle
Selection.TypeText Text:="sentence"
Selection.Font.Bold = wdToggle
Selection.TypeText Text:=" I am inserting." & vbCr

End Sub