我正在尝试将两个数据系列与日期进行比较,而在第三列中仅显示两个数据系列中共同的日期(以降序模式排序)。我的一个朋友帮我整理了一些似乎有效的代码,但是当我有相当长的一系列数据时,似乎需要很长时间来生成结果。有没有办法以不同的方式编写可能更快计算的代码? (我目前正在使用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
答案 0 :(得分:1)
您可以在没有VBA的情况下执行此操作。
在C列中,使用COUNTIF提取仅出现在A列和B列中的日期
=IF(COUNTIF($B$2:$B$7,"="&A2) > 0, A2, 0)
然后在D列中使用数组公式(来自here)来排序和删除空格。不要忘记选择范围,然后按下控制键,切换并输入。
=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))
答案 1 :(得分: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并检查Match2中的匹配公式是否成功/失败。成功=匹配,这意味着共同的日期。然后将它们打印到另一列。希望这有帮助!