首页 > 解决方案 > Excel - 在给定特定年份和月份值的范围内查找一个月的最后一天

问题描述

在此处输入图像描述

我想知道可以使用哪些 Excel/VBA 函数在具有特定年份和月份输入值的范围内查找一个月的最后一天。例如,对于 '1995' 和 '3',它应该返回 '3/31/1995'。对于 '1995' 和 '4',它应该返回 '4/28/1995'。

请注意,“04/1995”的实际最后一天是“4/30/1995”。我正在寻找范围内的最后一天,“1995 年 4 月 28 日”,所以我不能盲目地使用 EOMONTH 函数。

标签: excelvba

解决方案


下面是一个 VBA 解决方案,它应该可以工作并且速度相对较快。

我将范围内与年份和月份匹配的所有项目添加到ArrayList. 然后,我按升序对该列表进行排序并选择列表中的最后一项(该项应具有集合中的最大值)。

这是在不到一秒钟的时间内运行通过大约 800 个项目的列表。

功能:

Option Explicit

Public Function MaxDateInRange(SearchRange As Range, _
                               YearNumber As Long, _
                               MonthNumber As Long) As String
    Dim cell        As Range
    Dim ListIndex   As Long
    Dim List        As Object: Set List = CreateObject("System.Collections.ArrayList")
    
    'Go through all cells, and all items that match the month and year to a list
    For Each cell In SearchRange
        If IsDate(cell) Then
            If Month(cell) = MonthNumber And Year(cell) = YearNumber Then List.Add (cell)
        End If
    Next
    
    'Sort the list ascending, then select the last item in that list
    List.Sort
    ListIndex = List.Count - 1
    
    'Bounds check, to see if anything was found, otherwise return ""
    If ListIndex >= 0 Then
        MaxDateInRange = List(ListIndex)
    Else
        MaxDateInRange = vbNullString
    End If
    
End Function

用法:

Public Sub Example()
    Dim rng As Range: Set rng = Sheets(2).Range("D1:D795")
    Dim t   As Double
    t = Timer
    
    Debug.Print MaxDateInRange(rng, 2019, 3)
    Debug.Print MaxDateInRange(rng, 2019, 4)

    Debug.Print "Process took " & Timer - t
End Sub

基于示例数据的调试输出:

2019-03-28
2019-04-25
Process took 0.04296875

推荐阅读