2017-07-26 126 views
1

我想要實現以下功能: 在我的Excel表格中,我有一組數據,我通過創建一個「搜索框」來應用動態過濾。 過濾本身工作正常,但沒有問題,但是,我想進一步改進它,通過突出顯示紅色過濾行中的文本(輸入到搜索框中)。 我附上了我想要在最終版本中看到的屏幕截圖。帶高亮顯示的動態搜索 - Excel VBA

enter image description here

任何想法,這可怎麼進入我當前的代碼?

一如既往,任何幫助非常感謝! 謝謝!

下面是我使用的動態過濾代碼:

Private Sub TextBox1_Change() 
Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 


If Len(TextBox1.Value) = 0 Then 
    Sheet1.AutoFilterMode = False 
Else 
    If Sheet1.AutoFilterMode = True Then 
     Sheet1.AutoFilterMode = False 
     End If 

    Sheet1.Range("B4:C" & Rows.Count).AutoFilter field:=1, Criteria1:="*" & TextBox1.Value & "*" 

    End If 

Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 
End Sub 

回答

0

考慮這樣的事情 - 寫在工作表中以下內容:

Option Explicit 

Private Sub Worksheet_Change(ByVal Target As Range) 

    If Target.Count > 1 Then Exit Sub 
    If Target <> Range("a1") Then Exit Sub 
    SelectAndChange (Target) 

End Sub 

Private Sub SelectAndChange(strValue As String) 

    Dim rngCell  As Range 
    Dim rngRange As Range 
    Dim strLookFor As String 
    Dim arrChar  As Variant 
    Dim lngCounter As Long 

    If strValue = vbNullString Then Exit Sub 

    Application.EnableEvents = False 

    Set rngRange = Range("E1:E10") 
    rngRange.Font.Color = vbBlack 
    strLookFor = Range("A1").Value 

    For Each rngCell In rngRange 
     For lngCounter = 1 To Len(rngCell) - Len(strLookFor) + 1 
      If Mid(rngCell, lngCounter, Len(strLookFor)) = strLookFor Then 
       rngCell.Characters(lngCounter, Len(strLookFor)).Font.Color = vbRed 
      End If 
     Next lngCounter 
    Next rngCell 

    Application.EnableEvents = True 

End Sub 

E1:E10值將取決於從值在A1這樣的:

enter image description here

+0

謝謝你的代碼!這似乎與我的代碼一起工作,但是,有一個小問題。對我而言,如果我雙擊單元格(A1),字符只會變成紅色。我希望實時看到這一點。另外,出於某種原因,如果我刪除了文字,字符仍爲紅色。任何這些解決方案? :)否則,真的很好! – llorcs

+0

@llorcs - 要在「實時」中看到動作,請從代碼中刪除此行:'如果目標<>範圍(「a1」)然後退出子' – Vityata

+0

關於空單元格,使所有值都爲紅色,大約有10種方法來解決這個問題。其中之一是在代碼中添加'如果strValue = vbNullString Then Exit Sub'。我已經添加了它。 @llorcs – Vityata