在两个范围之间查找

时间:2017-06-08 16:23:44

标签: excel vba excel-vba udf

下午所有,我正在处理两列数据 - 其中一列有作者姓名,第二列有发布日期时间值。我想建立一个UDF来获取这两个范围,在author列中搜索特定的字符串,如果找到则返回发布列中的值。

数据与此类似;

enter image description here

一旦找到了我正在寻找的作者,我希望它能够查看发布时间并找到最小值。

例如,如果我在上面寻找作者Ben,那么返回的值应该是08/06/2014 17:15。

如果我使用的数据总是采用相同的格式,那么我会建立一个数组公式来创建一个MINIF,但这些范围显示的列总是不同的,最简单的选项将是最终用户的UDF可以把这两个范围放进去。

提前感谢您的帮助。

干杯

2 个答案:

答案 0 :(得分:1)

您的UDF可能是这样的,不需要Office 365功能:

Function MinDateByAuthor(author As String, rngNames As Range, rngDates As Range) As Date
  MinDateByAuthor = Application.Evaluate("Aggregate(15, 6," & _
    rngDates.Address(External:=True) & "/(" & _
    rngNames.Address(External:=True) & "=""" & author & """),1)")
End Function

您可以像=MinDateByAuthor("Ben", A2:A100, B2:B100)

一样使用它

您也可以放置一些单元格地址,而不是硬编码的"Ben"

TBH,你所做的所有UDF都有助于输入一些初始公式。 并且您可能希望通过允许完整的列引用(A:A, B:B)而不会敏感的缓慢来使其更容易。在上面的UDF中,可以这样做,但正如@ScottCraner所建议的那样,我们可以让它更快地运行:

Function MinDateByAuthor2(author As String, ByVal rngNames As Range, ByVal rngDates As Range) As Date
  Set rngNames = Intersect(rngNames, rngNames.Parent.UsedRange)
  Set rngDates = Intersect(rngDates, rngDates.Parent.UsedRange)

  ' The rest is the same ...
  MinDateByAuthor2 = Application.Evaluate("Aggregate(15, 6," & _
    rngDates.Address(External:=True) & "/(" & _
    rngNames.Address(External:=True) & "=""" & author & """),1)")
End Function

您会注意到=MinDateByAuthor2(A3,A:A,B:B)的计算速度比=MinDateByAuthor(A3,A:A,B:B)快。

答案 1 :(得分:0)

假设看起来像这样,只需更改此行:

If Cells(x,1).Value="ben" Then 'or whatever name you chose

如果你想让它成为其他作者

 Dim x As Integer
 Dim y As Integer
 Dim a As Date

      Application.ScreenUpdating = False
      ' Set numrows = number of rows of data.
      NumRows1 = Range("A1", Range("A1").End(xlDown)).Rows.Count
      NumRows2 = Range("B1", Range("B1").End(xlDown)).Rows.Count

      Range("A1").Select

      For x = 1 To NumRows1
           If Cells(x,1).Value="ben" Then 'or whatever name you chose
             If IsEmpty(a) Then
                A = Cells(x,2)
             End If
             If DateValue(Cells(x,2))<A Then
                  A = Cells(x,2)    
             End If
           End If
      Next