Word VBA - 在表格中选择从给定单词到段落末尾但不是整个单元格

时间:2017-12-20 08:09:42

标签: vba ms-word find

尝试选择并用红色标记指定的文本,从" Depend" 开始到单元格的末尾,但不是整个单元格。 代码示例:

With Selection
        Set obj_Tbl = .Tables(1)
        .Tables(1).Columns(2).Select ' Why so stupid? there is the conditional formatting
        For Each obj_Row In obj_Tbl.Rows
           With obj_Row.Cells(3)
                If InStr(1, obj_Row.Cells(3), "Depend") > 0 Then
                    obj_Row.Cells(3).Range.Characters(InStr(1, obj_Row.Cells(3), "Depend")).Select
                    Selection.EndKey Unit:=wdLine, Extend:=wdExtend
                    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
                    Selection.Font.Color = RGB(192, 0, 0)
                End If
           End With
       Next 
End With

当"依赖"写在一行。但如果文字看起来像

Depends from Something 
Too Long to Be Shown In One Line

我在选择时遇到麻烦,只选择一行。

Selection.EndOf Unit:=wdParagraph 'selects the entire cell
Selection.EndKey Unit:=wdParagraph 'is not supported

1 个答案:

答案 0 :(得分:0)

您可以使用MoveRight并计算从Length of the Cell - Your Current Position向右移动的单位。

Sub Test()
Dim count As Long
With Selection
        Set obj_Tbl = .Tables(1)
        .Tables(1).Columns(2).Select
         For Each obj_Row In obj_Tbl.Rows
           With obj_Row.Cells(3)
                If InStr(1, obj_Row.Cells(3), "Depend") > 0 Then
                    obj_Row.Cells(3).Range.Characters(InStr(1, obj_Row.Cells(3), "Depend")).Select
                    count = Len(obj_Row.Cells(3).Range) - InStr(1, obj_Row.Cells(3), "Depend")
                    Selection.MoveRight Unit:=wdCharacter, count:=count - 2, Extend:=wdExtend
                    Selection.Font.Color = RGB(192, 0, 0)
                End If
           End With
       Next
End With
End Sub