如何使函数递归

问题描述 投票:0回答:2

我有一大堆数据(差不多12k行)。我想搜索A列中的关键字(例如:名称“),然后将其对应的值从列B移动到新工作表。我有这个工作,但无法弄清楚如何使其递归所以它看起来所有12k A栏中的条目。请帮忙。

请参阅下面的脚本,但需要递归

Sub Test()

With Sheets("original")
    If .Range("A24").Value = "Name        " Then
        Sheets("new").Range("A1").Value = .Range("B24").Value
    End If
End With

End Sub
excel vba
2个回答
0
投票

您可以循环遍历单元格范围并使用offset来获取B列中的值以放置在新工作表中。它不需要递归

Sub Test()
Dim c As Range
Dim iRow As Long
    iRow = 1
    For Each c In Sheets("original").Range("A:A")
    If c.Value = "Name        " Then
        Sheets("new").Cells(iRow, 1).Value = c.Offset(0, 1).Value
        'move to the next row
        iRow = iRow + 1
    End If
    Next c
End Sub

0
投票

这里是使用标准2-D阵列的示例。字典是另一种基于数组的选项。自动筛选或高级筛选器不需要数组和/或遍历行。

请注意,这不会遍历“A列中的所有行”。当B列中没有可以返回的值时,它会停止循环。

Sub Test2()
    '
    'https://stackoverflow.com/questions/55928149
    '

    Dim i As Long, arr As Variant, bees As Variant

    With Worksheets("original")

        'collect source values
        arr = .Range(.Cells(7, "A"), .Cells(.Rows.Count, "B").End(xlUp)).Value2

        'prepare target array
        ReDim bees(1 To 1, 1 To 1)

        'loop through source value array and retain column B based on condition
        For i = LBound(arr, 1) To UBound(arr, 1)
            'case insensitive comparison
            If LCase(arr(i, 1)) = LCase("Name        ") Then
                'assign column B value to target array
                bees(1, UBound(bees, 2)) = arr(i, 2)
                'make room for next matching value
                ReDim Preserve bees(1 To 1, 1 To UBound(bees, 2) + 1)
            End If
        Next i

        'trim off the last unused element of the target array
        ReDim Preserve bees(1 To 1, 1 To UBound(bees, 2) - 1)

    End With

    'add new worksheet at end of worksheets queue
    With Worksheets.Add(after:=Worksheets(Worksheets.Count))

        'rename new worksheet
        .Name = "bees"

        'put target array in new worksheet starting at A2
        .Cells(2, "A").Resize(UBound(bees, 2), UBound(bees, 1)) = _
            Application.Transpose(bees)

    End With

End Sub

推荐问答