【问题标题】:How to get the first non-empty value amongst 4 dates如何在 4 个日期中获取第一个非空值
【发布时间】:2021-06-22 22:08:27
【问题描述】:

对于 200k+ 行的列表,我有 4 个日期值按重要性降序排列。 重要性顺序为 date1 > date2 > date3 > date4。有时,日期值中没有值或单个空格字符串。如果发生这种情况,我将需要进入下一个最重要的日期。 date4 将始终是正确的日期值。

我在下面有一个简单的函数,它返回所需的值,但我想知道是否有任何方法可以让它更快?我的列表很容易膨胀到 500K+ 行,并且会占用大量时间

Function getConEndDate(date1 As Date, date2 As Date, date3 As Date, date4 As Date) As Date
Dim endDate As Date

If Len(date1) > 2 Then
    endDate = date1
ElseIf Len(date2) > 2 Then
    endDate = date2
ElseIf Len(date3) > 2 Then
    endDate = date3
Else
    endDate = date4 + 30
End If

getConEndDate = endDate
End Function

【问题讨论】:

  • 这里有一些根本错误:您的函数接受Date 类型的参数。 Len(AnyDate)始终 > 2。如果您传递空单元格,它将转换为“00:00:00”,如果您传递单个空格字符串,则会出现运行时错误。此外,该函数本身很快(调用它 1,000,000 次有效日期在我的硬件上运行时间

标签: excel vba


【解决方案1】:

如果您正在读取某个范围内的日期,您可以尝试这样的操作...

Function getConEndDate(rng As Range) As Date
Dim endDate         As Date
Dim i               As Long
Dim endDateFound    As Boolean

For i = 1 To rng.Cells.Count - 1
    If IsDate(rng.Cells(i).Value) Then
        endDate = rng.Cells(i).Value
        endDateFound = True
    End If
Next i
If endDateFound Then
    getConEndDate = endDate
Else
    getConEndDate = rng.Cells(rng.Cells.Count) + 30
End If

End Function

那么如果你的日期在 A2:A5000 范围内,你可以这样使用它...

=getConEndDate(A2:A5000)

此函数假定范围中的最后一个单元格始终是您在描述中所述的日期,否则您也可以检查最后一个单元格以查看它是否是日期,如果没有找到之前的日期,则添加 30在提供的范围内。

更新代码:

Function getConEndDate(rng As Range) As Date
Dim endDate         As Date
Dim arr             As Variant
Dim i               As Long
Dim endDateFound    As Boolean

arr = rng.Value

For i = 1 To UBound(arr, 1) - 1
    If IsDate(arr(i, 1)) Then
        endDate = arr(i, 1)
        endDateFound = True
    End If
Next i
If endDateFound Then
    getConEndDate = endDate
Else
    getConEndDate = arr(UBound(arr, 1), 1) + 30
End If

End Function

【讨论】:

  • 如果 OP 担心性能,那么首先将范围读入数组会更快。您也可以在收到日期后立即从循环中Exit For
  • 是的。我同意你的看法。
猜你喜欢
  • 2023-02-18
  • 2011-02-15
  • 1970-01-01
  • 2021-08-16
  • 2020-09-04
  • 1970-01-01
  • 2015-12-23
  • 2014-12-14
  • 2016-11-18
相关资源
最近更新 更多