Word VBA - 在表格中从给定单词到段落末尾但不是整个单元格中选择
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Word VBA - 在表格中从给定单词到段落末尾但不是整个单元格中选择相关的知识,希望对你有一定的参考价值。
尝试选择并用红色标记从“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
当“Depend”写在一行时,这可以正常工作。但如果文字看起来像
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
答案
您可以使用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
以上是关于Word VBA - 在表格中从给定单词到段落末尾但不是整个单元格中选择的主要内容,如果未能解决你的问题,请参考以下文章