簡體   English   中英

Excel VBA:查找具有多個條件的單元格的值的方法

[英]Excel VBA: Way to find the value of a cell with multiple criteria

我有一個大型文件,在一個工作表中包含3列和23393行。 列A表示日期,列B表示整數,第三列表示值。 我想找到具有多個條件的單元格(在第三列中)的值。

1)第一個標准是一個日期(它從2008年1月1日變為2009年12月31日)

2)第二個標准是整數(從1變為32)

謝謝

簡單方法怎么樣?

Function find(ByVal criteria1 As Date, ByVal criteria2 As Integer) As Variant

    For i = 2 To 300001
        If Cells(i, 1).Value = criteria1 Then
            If Cells(i, 2).Value = criteria2 Then
                find = Cells(i, 3).Value
                Exit Function
            End If
        End If
    Next i

    find = "N/A"

End Function

你可以測試它運行一個像這樣的簡單宏:

Sub storeFoundValues()

    Dim matches(2) As Variant
    Dim date1, date2 As Date
    Dim int1, int2 As Integer

    date1 = DateSerial(2015, 7, 15)
    int1 = 3
    matches(1) = find(date1, int1)
    Cells(1, 5) = matches(1) ' test the output

    date2 = DateSerial(2016, 1, 10)
    int2 = 2
    matches(2) = find(date2, int2)
    Cells(1, 6) = matches(2) ' test the output

End Sub

在具有30.000條記錄的工作表中花了不到一秒的時間。

在此輸入圖像描述

例如:

=INDEX(C1:C20,SUMPRODUCT(--(A1:A20=DATEVALUE("6/17/2009"))*(B1:B20=25)*ROW(1:20)))

在此輸入圖像描述

此方法假定只有一行符合條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM