Vba 将查找限制为Word中的文本选择(而不是整个文档)

Vba 将查找限制为Word中的文本选择(而不是整个文档),vba,ms-word,Vba,Ms Word,我试图将Word文档中的红色文本搜索限制为单个表单元格。不管我怎么做,都会搜索整个文档。我已取得以下方面的进展: Sub FindRedText() Dim MyArray() As String Dim result As String Dim i As Long 'Dim RngFnd As Range i = 0 Selection.SelectCell 'Set RngFnd = Selection.Range Selection.Find.ClearFor

我试图将Word文档中的红色文本搜索限制为单个表单元格。不管我怎么做,都会搜索整个文档。我已取得以下方面的进展:

Sub FindRedText()
    Dim MyArray() As String
    Dim result As String
    Dim i As Long

'Dim RngFnd As Range

i = 0

Selection.SelectCell
'Set RngFnd = Selection.Range
Selection.Find.ClearFormatting
Selection.Find.Font.Color = wdColorRed

Do While Selection.Find.Execute = True
'If RngFnd.InRange(RngFnd) Then
        ReDim Preserve MyArray(i)
        MyArray(i) = Selection
        i = i + 1
'Else
'End If
    Loop

    If i = 0 Then
        MsgBox "No Red Text"
        Exit Sub
    End If

    For i = LBound(MyArray) To UBound(MyArray)
        result = Join(MyArray, ", ")
    Next i

End Sub
我已在中留下我的注释,以显示将当前选择设置为范围的失败尝试。执行此操作时,单元格中的所有文本都会复制到数组中

例如,假设我有以下几点:

Sub FindRedText()
    Dim MyArray() As String
    Dim result As String
    Dim i As Long

'Dim RngFnd As Range

i = 0

Selection.SelectCell
'Set RngFnd = Selection.Range
Selection.Find.ClearFormatting
Selection.Find.Font.Color = wdColorRed

Do While Selection.Find.Execute = True
'If RngFnd.InRange(RngFnd) Then
        ReDim Preserve MyArray(i)
        MyArray(i) = Selection
        i = i + 1
'Else
'End If
    Loop

    If i = 0 Then
        MsgBox "No Red Text"
        Exit Sub
    End If

    For i = LBound(MyArray) To UBound(MyArray)
        result = Join(MyArray, ", ")
    Next i

End Sub
在表单元格1中,选择1:红色文本1、蓝色文本1、红色文本2 在表单元格1,2中:红色文本3


我的宏当前将红色文本1、红色文本2和红色文本3放入我的数组和最终结果字符串中。我只需要红色文本1和红色文本2,即只搜索所选单元格。

尝试以下操作:首先选择区域,然后运行此操作

Sub FindSelectionColorText()
Selection.Find.ClearFormatting

With Selection.Find
    .Text = ""
    .Replacement.Text = ""
    .Font.Color = RGB(255, 0, 0)  'wdColorRed
    .Forward = True
    .Wrap = wdFindAsk
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
    Selection.Find.Execute
End Sub

“如果答案有效,请标记为“答案”和/或“向上投票”,否则请评论所发生的事情。

谢谢,但按我的需要不起作用。我需要在没有任何用户输入的情况下限制对一个单元格的访问。您所说的限制一个单元格是什么意思。您想从选择文本中搜索红色文本,还是想搜索红色预定义文本?