1

我正在尝试将两个数据系列与日期进行比较,并且在第三列中仅显示两个数据系列中常见的日期(以降序模式排序)。我的一个朋友帮助我整理了一些似乎可以工作的代码,但是当我拥有相当长的一系列数据时,生成结果似乎需要很长时间。有没有办法以不同的方式编写这段代码,可以更快地计算?(我目前正在使用 excel 2010。

我在 D2 上输入然后将其复制下来的功能是:=next_duplicate(A2:$A$535,B2:$B$535,D1:$D$1)

在此处输入图像描述

Function next_duplicate(list1, list2, excluded)
   For Each c In list1
    If WorksheetFunction.CountIf(excluded, c) = 0 Then
        If WorksheetFunction.CountIf(list2, c) > 0 Then
            next_duplicate = c
            Exit For
        End If
    End If
Next c

If next_duplicate = 0 Then
    next_duplicate = "N/A"
End If
End Function
4

2 回答 2

1

您可以在没有 VBA 的情况下执行此操作。

在 C 列中,使用 COUNTIF 提取仅出现在 A 列和 B 列中的日期

=IF(COUNTIF($B$2:$B$7,"="&A2) > 0, A2, 0)

然后在 D 列中使用数组公式(从这里)对空格进行排序和删除。不要忘记选择范围,然后按 control、shift 和 enter。

=INDEX(C2:C7, MATCH(LARGE(IF(ISBLANK(C2:C7), "", IF(ISNUMBER(C2:C7), COUNTIF(C2:C7, "<"&C2:C7), COUNTIF(C2:C7, "<"&C2:C7)+SUM(IF(ISNUMBER(C2:C7), 1, 0))+1)), ROW()-ROW($D$2)+1), IF(ISBLANK(C2:C7), "", IF(ISNUMBER(C2:C7), COUNTIF(C2:C7, "<"&C2:C7), COUNTIF(C2:C7, "<"&C2:C7)+SUM(IF(ISNUMBER(C2:C7), 1, 0))+1)), 0))
于 2012-08-21T14:41:16.373 回答
0

如果@Dan 的解决方案有效,请继续使用,因为公式解决方案通常更酷:) 如果您需要使用 VBA,您可以试试这个:

Sub Common()

Dim Date1 As Range
Dim Date2 As Range
Dim CommonDates() As Variant
Dim UniqueDates As New Collection

Set Date1 = Range("A2:A6")
Set Date2 = Range("B2:B6")

' Change the max array size to equal the length of Date1
' This is arbitrary and could be more efficient, for sure :)
ReDim CommonDates(Date1.Count)

' Set a counter that will increment with matches
i = 0

' Since a match needs to be in both, iterate through Date1 and check
' if the Match function returns a True value when checking Date2.
' If so, add that value to the CommonDates array and increment the counter.
For Each DateVal In Date1
  If IsError(Application.Match(DateVal, Date2, 0)) = False Then
    CommonDates(i) = DateVal.Value
    i = i + 1
  End If
Next

' Filter out dupes (in case that is possible - if not, this can be removed
' and the bottom part reworked
On Error Resume Next
For Each Value In CommonDates
  UniqueDates.Add Value, CStr(Value)
Next Value

' Now go to the first cell in your Common Dates range (I'm using C2) and
' print out all of the results
Range("C2").Activate
For j = 1 To UniqueDates.Count
  ActiveCell.Value = UniqueDates(j)
  ActiveCell.Offset(1).Activate
Next j

' Back to the beginning
Range("C2").Activate

' Use this if you don't need to filter dupes
'For Each r In CommonDates
'  ActiveCell.Value = r
'  ActiveCell.Offset(1).Activate
'Next

End Sub

它基本上遍历 Date1 并检查 Match 公式在 Date2 中是否成功/失败。成功=匹配,这意味着一个共同的日期。然后将它们打印到另一列。希望这可以帮助!

于 2012-08-21T15:03:21.923 回答