Home » excel » excel – VBA Dynamic Search mode with dynamic

excel – VBA Dynamic Search mode with dynamic

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have my script which enables me to search into my data by typing in my TextBox.
The problem is that mine is static (for example row 6 to 30).
If I add a new row, it won’t be taken by my script.
I guess I have to use variables instead of pre-defined range but I don’t know how to do it.

Best regards

Option Compare Text

Private Sub TextBox1_Change()

    Application.ScreenUpdating = False

    Range("E8:E30").Interior.ColorIndex = 24

    If TextBox1 <> "" Then
        For ligne = 8 To 30
            If Cells(ligne, 5) Like "*" & TextBox1 & "*" Then
                Cells(ligne, 5).Interior.ColorIndex = 43
            End If
        Next
    End If
End Sub
How to&Answers:

I prefer to use a For each loop. You should also always fully qualify your references.

Private Sub TextBox1_Change()
    Application.ScreenUpdating = False
    Dim cell As Range, Target As Range
    With Worksheets("Sheet1")
        Set Target = .Range("E8", .Range("E" & .Rows.Count).End(xlUp))
        Target.Interior.ColorIndex = 24

        For Each cell In Target
            If cell.Value Like "*" & TextBox1 & "*" Then cell.Interior.ColorIndex = 43
        Next

    End With
    Application.ScreenUpdating = True
End Sub

Answer:

Thanks a lot TinMan, I just added back this If TextBox1 <> "" Then , otherwise the Column E is already green at the beginning.

Moreover, you are right, that was my reference http://www.blog-excel.com/creer-un-champ-de-recherche-vba/

Have a good day 🙂

Guillaume