从VBA开始和结束date提取几个月 – Excel

我有一个从开始和结束date派生的date列表,例如:

01/10/2011 – 通过.. – – 01/01/2012

在VBA中,我怎样才能从这两个date之间检索一个数组,所以输出将类似于:

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

有这个容易的解决scheme吗?

要在VBA中完全在没有对工作表进行操作的情况下执行此操作:

您可以通过循环查看date,提取月份和年份并将其添加到集合并将密钥设置为月份和年份的值来创build具有唯一月份和年份的集合。

如果另一个date的集合中已有相同的月份和年份,集合将不会复制,因为已经设置了月份和年份的关键字,并且会产生错误。 通过禁用error handling(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 (eg 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