excel - Excel - 在给定特定年份和月份值的范围内查找一个月的最后一天
问题描述
我想知道可以使用哪些 Excel/VBA 函数在具有特定年份和月份输入值的范围内查找一个月的最后一天。例如,对于 '1995' 和 '3',它应该返回 '3/31/1995'。对于 '1995' 和 '4',它应该返回 '4/28/1995'。
请注意,“04/1995”的实际最后一天是“4/30/1995”。我正在寻找范围内的最后一天,“1995 年 4 月 28 日”,所以我不能盲目地使用 EOMONTH 函数。
解决方案
下面是一个 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
推荐阅读
- google-apps-script - 如何从谷歌表格下载PNG图表
- arrays - NODEJS:想要创建一个对象数组,每个对象中只有一个键的值设置为空
- java - 尝试初始化 posModel 时,Android 中的 OpenNLP 获取 FileNotFoundException
- python - 使用索引的 KeyError
- android - 将 Android Studio 文件传输到另一台 PC
- reactjs - React 功能组件中的依赖 api 调用
- typescript - 使用多态 this 在打字稿中实现类型安全克隆而不使用类型转换
- javascript - 如何在不使用事件监听器的情况下检查单击的元素?
- sublimetext - 如何在 Sublime 上启用着色文本
- amazon-s3 - 如何将 png 文件上传到 S3 Bucket?