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

时间:2017-03-04 01:02:14

标签: excel vba

我想在G列中搜索这两个交替的文本,并在B列中输出它们的行号,从B2开始。

数据类似于:

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

它目前只找到第一个“充电”,输出将为“$ G $ 1”,但它不会继续找到所有其他值。我还希望输出只是“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

2 个答案:

答案 0 :(得分:1)

如果您的意思是希望在let deck = [{...}, {...}, {...}]; function returnCard(deck) { let element = deck[Math.floor(Math.random() * deck.length)]; removeCard(element); return element; } function removeCard(card) { deck = deck.filter(function(el) { return el.name !== card.name; }); } 中用逗号分隔两行,则应该这样做:

B2

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

或者如果您想要1,4B2

C2

并将它们放在Range("B2:c2").value = Application.Match _ (Array("Charge", "Discharge"), Sheets("General Text").Columns("G"), 0) B2中:

B3

最后,你想要找到所有这些,但是相继:

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

答案 1 :(得分:1)

另一种可能性,使用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)