VBA Excel使用通配符和已parsing的对象引用
我试图让input框中input的searchstring与*通配符一起使用,以search所选范围内string的实例。
Sub color() Dim myRange As Range, value As String, wild As Icon value = InputBox("Search String:") If value = vbNullString Then Exit Sub Range("A1").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select For Each myRange In Selection If myRange.value = "*" & value & "*" Then myRange.Interior.ColorIndex = 3 End If Next myRange End Sub
另一种可能性:为什么要使用通配符? 已经有一个VBA函数来testing子串。 尝试:
If InStr(myRange.value,value) > 0 Then
而不是通配符:
Sub color() Dim myRange As Range, valuee As String valuee = InputBox("Search String:") If valuee = vbNullString Then Exit Sub Range("A1").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select For Each myRange In Selection If InStr(myRange.value, valuee) > 0 Then myRange.Interior.ColorIndex = 3 End If Next myRange End Sub
我们也可以使用.Find方法。
编辑#1:
这是一个使用.Find和.FindNext的版本:
Sub color2() Dim myRange As Range, valuee As String valuee = InputBox("Search String:") If valuee = vbNullString Then Exit Sub Range("A1").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select Set myRange = Selection.Find(what:=valuee, after:=Selection(1)) If myRange Is Nothing Then MsgBox "no value" Exit Sub End If myRange.Interior.ColorIndex = 3 st = myRange.Address(0, 0) Do Until myRange Is Nothing Set myRange = Selection.FindNext(after:=myRange) If myRange.Address(0, 0) = st Then Exit Do myRange.Interior.ColorIndex = 3 Loop End Sub