我使用下面的代码来查找列。
Set FinColumn = .Find(What:="Tax", AFter:=.Cells(1, 1), LookIn:=xlValues, LookAt _
:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).
如果我有下面的列,它应该识别。
Tax Tax&Fee Tax&Fee1
如何更改上面的set语句以查找以上所有列。我可以实现任何搜索条件。
谢谢,
Chaitu
答案 0 :(得分:2)
虽然我的第一个答案是正确的,但还不完整。以下代码循环查找包含“tax”的每个单元格,并在所有单元格都已处理后停止。
您问题的直接答案是xlWhole
替换xlPart
。但是,有些错误会阻止您的代码工作;例如,您没有定义查找操作的范围。我在.Cells
前添加了.Find
。
希望这有帮助。
Option Explicit
Sub FindAllTax()
Dim ColCrnt As Long
Dim ColLast As Long
Dim FinColumn As Range
Dim RowCrnt As Long
Dim RowLast As Long
RowLast = 0
ColLast = 0
With Sheets("Sheet6")
Set FinColumn = .Cells.Find(What:="Tax", After:=.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Do While True
If FinColumn Is Nothing Then
' No occurrence of "Tax" found
Exit Do
End If
RowCrnt = FinColumn.Row
ColCrnt = FinColumn.Column
If RowCrnt < RowLast Or _
(RowCrnt = RowLast And ColCrnt < ColLast) Then
' Current cell is above last cell so have looped after finding
' all values.
Exit Do
End If
Debug.Print "Cells(" & RowCrnt & ", " & ColCrnt & ")=" & _
.Cells(RowCrnt, ColCrnt).Value
RowLast = RowCrnt
ColLast = ColCrnt
Set FinColumn = .Cells.FindNext(FinColumn)
Loop
End With
Debug.Print "All cells containing ""tax"" processed"
End Sub
答案 1 :(得分:1)
A1 =税
B10 =税费和费用
C15 =税费和费用1
D20 = 123Tax
G45 = DoggyTax
如果您只想搜索税*,税,税和费用以及税费和费用1,该怎么办?
此外,当您在所有单元格中进行搜索时,您必须指定范围。这是一个简单的例子
Option Explicit
Sub Sample()
Dim oRange As Range, aCell As Range, bCell As Range
Dim ws As Worksheet
Dim ExitLoop As Boolean
Dim SearchString As String, FoundAt As String
On Error GoTo Err
'~~> The Sheet where the search has to be performed
Set ws = Worksheets("Sheet1")
'~~> In All cells
Set oRange = ws.Cells
'~~> Search string
SearchString = "Tax*"
Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'~~> If search was found
If Not aCell Is Nothing Then
Set bCell = aCell
FoundAt = aCell.Address
Do While ExitLoop = False
Set aCell = oRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
FoundAt = FoundAt & ", " & aCell.Address
Else
ExitLoop = True
End If
Loop
Else
MsgBox SearchString & " not Found"
End If
MsgBox "The Search String has been found these locations: " & FoundAt
Exit Sub
Err:
MsgBox Err.Description
End Sub
您可以在下面提到的链接中找到有关FIND()和FINDNEXT()的更多信息。
TOPIC:.Find和.FindNext在Excel VBA中
LINK :http://siddharthrout.wordpress.com/2011/07/14/find-and-findnext-in-excel-vba/
注意:如果您想查找“税”的所有实例,那么您不需要外卡。所有你需要做的就是使用Tony建议的以下内容。
LookAt:=xlPart
HTH
西特