查找包含两个交替文本的单元格的行数

我想searchG列这两个交替的文本,并输出他们的行号在列B,从B2开始。

数据看起来像这样:

Row 1 Charge 2 7 3 7 4 Discharge 5 2 6 Charge 7 9 

目前只find第一个“Charge”,输出结果为“$ G $ 1”,但不会继续find其他任何值。 我也想输出只是“1”而不是“$ G $ 1”

 Sub RowFinder() Dim Found As Range Dim SearchVal(1 To 2) As String SearchVal(1) = "Charge" SearchVal(2) = "Discharge" Set Found = ActiveWorkbook.Sheets("General Text").Columns("G").Find(what:=SearchVal(), _ LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext) If Not Found Is Nothing Then ActiveWorkbook.ActiveSheet.Range("B2").Value = Found.Row End If End Sub 

如果你的意思是你想在B2中用逗号隔开这两行,那么应该这样做:

 Sub RowFinder() Range("B2").value = Join(Application.Match _ (Array("Charge", "Discharge"), Sheets("General Text").Columns("G"), 0), ",") End Sub 

输出在“B2”中: 1,4

或者如果你想要他们在B2C2

 Range("B2:c2").value = Application.Match _ (Array("Charge", "Discharge"), Sheets("General Text").Columns("G"), 0) 

并让他们在B2B3

 Range("B2:B3").value = Application.Transpose(Application.Match _ (Array("Charge", "Discharge"), Sheets("General Text").Columns("G"), 0)) 

最后,你想要find他们,但接连不断:

 Sub RowFinder() Dim rng As Range, j As Long, lastCell As Range, ar ar = Array("Charge", "Discharge") j = 2 With Sheets("General Text") Set lastCell = .Cells(.Rows.Count, "G").End(xlUp) Set rng = .Range("G1", lastCell) On Error GoTo Finished Do .Cells(j, "B").value = rng.row - 1 + Application.Match(ar(j Mod 2), rng, 0) Set rng = .Range("G" & .Cells(j, "B").value, lastCell) j = j + 1 Loop End With Finished: End Sub 

另一种可能性,使用Autofilter() ,从而避免循环:

 Sub RowFinder() Dim founds As Range With Worksheets("General Text") '<--| reference your worksheet With .Range("G1", .Cells(.Rows.count, "G").End(xlUp)) '<--| reference its column G cells from row 1 (header) down to last not empty one .AutoFilter Field:=1, Criteria1:=Array("Charge", "Discharge"), Operator:=xlFilterValues '<--| filter cells with "Charge" and "Discharge" If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Set founds = .Resize(.Rows.count - IIf(InStr("ChargeDischarge", .Cells(1)) > 0, 0, 1)).Offset(IIf(InStr("ChargeDischarge", .Cells(1)) > 0, 0, 1)).SpecialCells(xlCellTypeVisible) End With .AutoFilterMode = False If Not founds Is Nothing Then .Range("B2").Resize(founds.count) = Application.Transpose(Split(Replace(founds.Address(False, False), "G", ""), ",")) End With End Sub 

其中,如果列G在第1行中有“标题”,则可以更改:

 If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Set founds = .Resize(.Rows.count - IIf(InStr("ChargeDischarge", .Cells(1)) > 0, 0, 1)).Offset(IIf(InStr("ChargeDischarge", .Cells(1)) > 0, 0, 1)).SpecialCells(xlCellTypeVisible) 

至:

 If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Set founds = .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible)