2017-07-26 132 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