简体   繁体   English

Excel VBA:查找具有多个条件的单元格的值的方法

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

I have a large file that contain 3 columns and 23393 rows in a sheet. 我有一个大型文件,在一个工作表中包含3列和23393行。 columns A refer to date, column B refer to integer numbers and the third column refer to value. 列A表示日期,列B表示整数,第三列表示值。 I want to find the value of a cell (in third column) with multiple criteria. 我想找到具有多个条件的单元格(在第三列中)的值。

1)the first criteria is a date (it changes from 1/1/2008 to 12/31/2009) 1)第一个标准是一个日期(它从2008年1月1日变为2009年12月31日)

2)the second criteria is an integer number(it changes from 1 to 32) 2)第二个标准是整数(从1变为32)

Thanks 谢谢

What about the simple approach? 简单方法怎么样?

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

You can test it running a simple macro like this: 你可以测试它运行一个像这样的简单宏:

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

This took less than a second in a worksheet with 30.000 records. 在具有30.000条记录的工作表中花了不到一秒的时间。

在此输入图像描述

For example: 例如:

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

在此输入图像描述

This approach assumes that only one row will match the criteria. 此方法假定只有一行符合条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM