【发布时间】:2014-06-23 21:24:50
【问题描述】:
我有一个从开始日期和结束日期派生的日期列表,例如:
01/10/2011 - 到.. - 01/01/2012
在 VBA 中,如何从这两个日期之间检索月份数组,因此输出类似于:
Oct-2011
Nov-2011
Dec-2011
Jan-2012
有没有简单的解决方案?
【问题讨论】:
我有一个从开始日期和结束日期派生的日期列表,例如:
01/10/2011 - 到.. - 01/01/2012
在 VBA 中,如何从这两个日期之间检索月份数组,因此输出类似于:
Oct-2011
Nov-2011
Dec-2011
Jan-2012
有没有简单的解决方案?
【问题讨论】:
完全在 VBA 中完成此操作,无需对工作表执行操作:
您可以通过循环日期、提取月份和年份并将它们添加到集合中并将键设置为月份和年份的值来创建具有唯一月份和年份的集合。
如果另一个日期与集合中已经存在的相同月份和年份,则集合不会复制它,因为已经设置了月份和年份的键并会产生错误。通过禁用错误处理(On Error Resume Next),代码将跳过添加,因此不会在集合中复制它。
实践中的技术(使用 cmets)
Sub GetUniqueMonths()
Dim uniqueMonths As Collection
Set uniqueMonths = New Collection
Dim dateRange As Range
Set dateRange = Range("A1:A10") 'Change this to your range of dates
On Error Resume Next
Dim currentRange As Range
For Each currentRange In dateRange.Cells
If currentRange.Value <> "" Then
Dim tempDate As Date: tempDate = CDate(currentRange.Text) 'Convert the text to a Date
Dim parsedDateString As String: parsedDateString = Format(tempDate, "MMM-yyyy") 'Format the date into the required format (Oct-2011 etc)
uniqueMonths.Add Item:=parsedDateString, Key:=parsedDateString 'Add the parsed date into the collection
'An error will be thrown if the record already exists as the key has been set to the value (e.g. Oct-2011)
'With On Error Resume next set, it will ignore the error and continue to run without adding the record therefore no duplication of dates
End If
Next currentRange
On Error GoTo 0 'Enable default error trapping
'Loop through the collection and view the unique months and years
Dim uniqueMonth As Variant
For Each uniqueMonth In uniqueMonths
Debug.Print uniqueMonth
Next uniqueMonth
End Sub
【讨论】:
.Add 之前移动 OERN 这将确保不会抑制其他错误消息(如果有的话):)