vba:使用2个标准识别行并返回行中的其他数据

我试图find在spreadsheet1中查找两个条件的代码,并在spreadsheet2中find相应的行,并将spreadsheet2中的第三条数据返回到spreadsheet1。 我需要在vba中这样做,因为它会循环,因为我将一次又一次地完成,并且因为spreadsheet2中的数据从另一个数据库导入,并且会随时间而改变。 如果可能的话,如果代码也允许在电子表格2上标识第三条标准,那将是非常好的。

例如:Spreadsheeet 1

Product ID ActCode: A0003 11111 12345 22222 ... 

电子表格2

 ProductID ActivityCode DateDue 11111 A0001 7/15/15 11111 P7530 7/30/15 11111 A0003 8/1/15 12345 A0003 12/15/15 12345 A0007 1/1/15 22222 A0001 2/1/15 ... 

我想要Spreadsheet1结束的地方:

Spreadsheeet 1

  Product ID ActCode: A0003 11111 8/1/15 12345 12/15/15 22222 - ... 

过去几天我尝试了很多东西。 1)从未真正起作用的vlookup / index / match组合,2)通过productID和activitycode过滤电子表格2,然后复制到spreadsheet1可见的单元格 – 这种方法很有效,但速度很慢。 我会为许多活动代码做这个,所以我需要更快的东西(如果你想看,我可以发布代码)。 我目前正在尝试循环内循环。 不知道这是否是最好的方法,但这是迄今为止的代码。 它确实复制了一些date,但不是正确的 – 它也有点慢。

 Sub test() Application.ScreenUpdating = False Sheets("Spreadsheet1").Select Range("A2").Select ' Select A = the column with the product ID in it ' Set Do loop to stop when an empty cell is reached. Do Until IsEmpty(ActiveCell) Dim ConceptAct As String ConceptAct = "A0003" Dim ProductID ProductID = ActiveCell.Value Dim ConcDue Sheets("Spreadsheet2").Select Range("A2").Select 'The column with the ProductID in it Do Until IsEmpty(ActiveCell) If ActiveCell.Value = ProductID And ActiveCell.Offset(0, 1).Value = ConceptAct Then ConcDue = ActiveCell.Offset(0, 2).Value Exit Do End If ActiveCell.Offset(1, 0).Select Loop Sheets("Spreadsheet1").Select ActiveCell.Offset(0, 1) = ConcDue ' Step down 1 row from present location. ActiveCell.Offset(1, 0).Select Loop Application.ScreenUpdating = True End Sub 

为什么不能索引/匹配工作? 我能够得到,我认为,您的解决scheme与索引/匹配公式作为一个数组input。 以下是一切的截图:

在这里输入图像说明

索引/匹配可以使用多个条件来查找,只需将它们连接到Match()的第一个和第二个部分,然后按CTRL + SHIFT + ENTER以input数组。 这个formua会查看产品ID,然后是ActCode,返回date。

这是你在找什么?

我不清楚为什么使用本地工作表函数的两列标准公式不是apprpriate,而用户定义函数(aka UDF)将是从VBA的angular度来追求的一个途径。

 Function udf_Get_Two(sCode As Range, rCodes As Range, _ sProd As Range, rProds As Range, _ rDates As Range) Dim vCode As Variant, rw As Long, m As Long 'quick check to see if there is anything to find If CBool(Application.CountIfs(rCodes.Columns(1), sCode.Value, _ rProds.Resize(rCodes.Rows.Count, 1), sProd.Value)) Then rw = 0 For m = 1 To Application.CountIf(rCodes.Columns(1), sCode.Value) rw = rw + Application.Match(sCode.Value, rCodes.Columns(1).Resize(rCodes.Rows.Count - rw, 1).Offset(rw, 0), 0) If rProds(rw, 1) = sProd Then udf_Get_Two = rDates.Cells(rw, 1).Value Exit Function End If Next m End If End Function 

像其他工作表公式一样使用。 例:

 =udf_Get_Two(A2, Sheet2!$A$2:$A$7, $C$1, Sheet2!$B$2:$B$7, Sheet2!$C$2:$C$7) 

用于两列查找的UDF

请注意,返回值是原始的。 细胞应格式化为m / d / yy或按照您的喜好。