从VBA - Excel中的开始和结束日期中提取月份

时间:2013-09-16 10:40:54

标签: excel excel-vba vba

我有一个日期列表,源自开始日期和结束日期,例如:

01/10/2011 - 至... - 01/01/2012

在VBA中,如何从这两个日期之间检索月份数组,因此输出类似于:

Oct-2011
Nov-2011
Dec-2011
Jan-2012

这有一个简单的解决方案吗?

1 个答案:

答案 0 :(得分:5)

要在VBA中完全执行此操作而不对工作表执行任何操作:

您可以通过循环显示日期,提取月份和年份并将其添加到集合并将关键字设置为月份和年份的值来创建具有唯一月份和年份的集合。

如果另一个日期与集合中已存在的月份和年份相同,则集合将不会复制它,因为已经设置月份和年份的密钥将产生错误。通过禁用错误处理(On Error Resume Next),代码将跳过添加,从而不会在集合中复制它。

技术在行动(带评论)

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