有没有更快的方法在excel vba中搜索两个不同的长度范围?

时间:2015-03-16 02:59:58

标签: excel vba

我在一个范围内有一个id列表,我需要计算出现在另一个范围内的这些id的数量。范围有不同的长度,或者我会使用countifs

我编写了以下代码,但速度非常慢:

Function find_in_two_ranges_two_sheets(ws1 As String, col1 As Integer, ws2 As String, col2 As Integer)
    'first find if is in one range, then count if it in another range

    '  *** set up range of first worksheet ***
    Dim rows1 As Integer
    rows1 = Get_Rows_Generic(ws1, 1) ' get the number of rows on the first sheet
    Dim range1 As Range ' range of first search

    With Worksheets(ws1)
        Set range1 = .Range(.Cells(1, col1), .Cells(rows1, col1)) ' set the range being searchedin the first sheet
    End With

    '   *** set up range of second worksheet ***
    Dim rows2 As Integer
    rows2 = Get_Rows_Generic(ws2, 1) ' get the number of rows in second worksheet

    Dim range2 As Range
    With Worksheets(ws2)
        Set range2 = .Range(.Cells(1, col2), .Cells(rows2, col2)) ' set the range being searched in second sheet
    End With


    Dim constructed_id As String ' the raw string found in the first column
    Dim found2 As Range ' this will be used as the query in the second range.

    '   *** set up counting variables ***
    Dim n As Integer
    Dim counter As Integer
    counter = 0

     '   *** loop through ranges in first sheet and count the number of times each id is found in second sheet ***
    For n = 1 To 300 ' rows1
        constructed_id = "ObjectID(" & range1(n, 1) & ")"
        Set found2 = range2.Find(constructed_id, LookIn:=xlValues)
        If Not found2 Is Nothing Then
            counter = counter + 1
        End If
    Next n

    find_in_two_ranges_two_sheets = counter

End Function


Sub test_stuff()
    Dim x As Integer
    x = find_in_two_ranges_two_sheets("invitesOutput.csv", 3, "propertyOutput.csv", 3) 
    MsgBox "counter totaled " & x
End Sub

任何方式我都可以加快速度吗?

0 个答案:

没有答案