我希望找到包含给定文本的单元格(作为范围)。这可能吗?我希望能够找到与文本匹配的第一个单元格(遵循行和列的自然顺序)。
然后,一个更高级的问题,我可以提供一个正则表达式来做同样的事情吗?
谢谢你们:)
答案 0 :(得分:5)
以下是示例代码。将Range("A1:D10")
替换为您的范围,并将正则表达式模式ni函数RE6替换为您自己的。
Sub SUB1()
For Each c In Worksheets("Sheet1").Range("A1:D10").Cells
If RE6(c.Value) Then
c.Interior.ColorIndex = 7
END IF
Next
End Sub
Function RE6(strData As String) As String
Dim RE As Object, REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = False
.Global = False
.IgnoreCase = True
.Pattern = "[0-9][0-9][0-9][0-9][0-9][0-9]"
End With
Set REMatches = RE.Execute(strData)
RE6 = REMatches(0)
End Function
答案 1 :(得分:1)
我尝试将此添加到杰罗姆的回答中,但我不能直到我的变更经过同行评审。 20个小时后什么也没发生,所以我把它作为答案添加。
不要忘记整理宏录制器的输出。如果查找失败,查找返回一个范围,该范围将为Nothing。除非您包含停止此操作的代码,否则FindNext将循环播放。您需要以下内容:
Dim ColFind As Integer
Dim RngFind As Range
Dim AddrFirst As String
Dim RowFind As Integer
With ActiveSheet
' Cells can be replaced by any range, for example: Row(5), Columns(3)
' The After cell must be in the search range. It will be the last cell searched.
' Get the With dots on the search range and the after cell to match or
' you will get some very peculiar results.
' What can be, for example: "Th*" to find "The", "There", "Therefore", etc.
' or "Th??" to find "Them", "That", etc.
Set RngFind = .Cells.Find( ... LookIn:=xlValues, After:=.Range("A1"), _
SearchDirection:=xlNext ...)
If RngFind Is Nothing Then
' Code to handle failure
Else
AddrFirst = RngFind.Address
Do
ColFind = RngFind.Column
RowFind = RngFind.Row
' Code to handle found cell
' Use FindPrevious if the Search direction is xlPrevious if
' you want the cells to be found in sequence.
' Warning. I have found that if the Set is omitted, this statement
' overwrites the value of the first cell found with the value
' of the second cell found.
Set RngFind = .Cells.FindNext(RngFind)
Loop While AddrFirst <> RngFind.Address
End If
End With
答案 2 :(得分:0)
Cells.Find(What:=".GDAXI", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
Cells.FindNext(After:=ActiveCell).Activate
Cells.FindNext(After:=ActiveCell).Activate
这是使用Ctrl F时会发生什么的宏录制,然后是“查找下一个”功能。