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 に答える