VBA Excel 使用通配符和已解析的对象引用

VBA Excel using a wildcard and resolved object reference

我试图让在输入框中键入的搜索字符串与 * 通配符结合使用,以搜索所选范围内的字符串实例。

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 函数来测试子字符串。尝试:

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