【问题标题】:VBA Excel using a wildcard and resolved object reference使用通配符和解析对象引用的 VBA Excel
【发布时间】:2015-06-11 16:18:37
【问题描述】:

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

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

【问题讨论】:

  • 试试If myRange.value LIKE "*" & value & "*" Then。等于是二进制比较。 LIKE 是一种称为模式匹配的东西。

标签: vba excel search wildcard


【解决方案1】:

另一种可能: 为什么要使用通配符?已经有一个 VBA 函数来测试子字符串。试试:

If InStr(myRange.value,value) > 0 Then

【讨论】:

  • 谢谢!!完美运行!
  • 要使其不区分大小写,您可以使用 InStr(1,myRange.value,value,vbTextCompare)
【解决方案2】:

而不是通配符:

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

【讨论】:

  • 你能给我一个.Find方法的例子吗?
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 2011-08-12
  • 2021-09-13
  • 2015-08-28
  • 1970-01-01
相关资源
最近更新 更多