0

我有这段代码,它使用用户通过输入框输入的值来查找匹配项。我希望突出显示找到的数据,但我的代码没有这样做。

Dim holdstr As String
Dim fset As Range

holdstr = UCase(InputBox("Enter name"))

For i = 2 To Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

    If holdstr = Sheet1.Cells(i, 1).Value Then

        MsgBox "Record found!", vbInformation, "Message"

        txtFirst.Text = Sheet1.Cells(i, 1).Value
        txtLast.Text = Sheet1.Cells(i, 2).Value
        txtMid.Text = Sheet1.Cells(i, 3).Value

        With Selection.Interior
            .ColorIndex = 6
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
        End With

    End If
Next i
4

2 回答 2

1

我已经更改了您的比较方法,因此=您现在使用的是更可靠的函数,而不是使用运算符StrComp()

删除了不必要的变量。

将选择更改为匹配行的 A:C 列。尽量避免使用.Select.Selection

一旦找到匹配项,A、B、C 列中的单元格将被填充Yellow颜色

Sub HighlightDates()

    Dim holdstr As String
    holdstr = UCase(InputBox("Enter name"))

    For i = 2 To Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
        If StrComp(holdstr, Sheet1.Cells(i, 1).Value, vbTextCompare) = 0 Then
            MsgBox "Record found!", vbInformation, "Message"

            With Range("A" & i & ":C" & i).Interior
                .ColorIndex = 6
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
            End With
        End If
    Next i
End Sub
于 2013-09-11T11:26:22.613 回答
0

作为替代方案,它需要更多代码,但我更喜欢 Range.Find 循环

Sub tgr()

    Dim rngColor As Range
    Dim rngFound As Range
    Dim strName As String
    Dim strFirst As String

    strName = InputBox("Enter Name", "Highlight Name")
    If Len(strName) = 0 Then Exit Sub   'Pressed cancel

    With Sheet1.Range("A2", Sheet1.Cells(Rows.Count, "A").End(xlUp))
        If .Row < 2 Then Exit Sub   'No data
        .Resize(, 3).Interior.Color = xlNone   'Remove any prior highlighting
        Set rngFound = .Find(strName, .Cells(.Cells.Count), xlValues, xlPart)
        If Not rngFound Is Nothing Then
            strFirst = rngFound.Address
            Set rngColor = rngFound.Resize(, 3)
            Do
                Set rngColor = Union(rngColor, rngFound.Resize(, 3))
                Set rngFound = .Find(strName, rngFound, xlValues, xlPart)
            Loop While rngFound.Address <> strFirst
            rngColor.Interior.ColorIndex = 6
            MsgBox rngColor.Cells.Count / 3 & " records found!", vbInformation, "Search Completed"
        Else
            MsgBox "No matches found", , "No Matches"
        End If
    End With

End Sub
于 2013-09-11T16:15:02.663 回答