如何使用VBA突出显示数据

时间:2013-09-11 11:17:02

标签: excel vba excel-vba

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

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

2 个答案:

答案 0 :(得分:1)

我更改了您的比较方法,因此您现在使用名为StrComp()

的更可靠的函数,而不是使用=运算符

删除了不必要的变量。

将选择更改为匹配行的列A:C。尝试avoid using .Select or .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

答案 1 :(得分: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