【问题标题】:Extract months from start and end date in VBA - Excel从 VBA 中的开始和结束日期中提取月份 - Excel
【发布时间】:2014-06-23 21:24:50
【问题描述】:

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

01/10/2011 - 到.. - 01/01/2012

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

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

有没有简单的解决方案?

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    完全在 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
    

    【讨论】:

    • + 1 做得很好。但是,我建议在 .Add 之前移动 OERN 这将确保不会抑制其他错误消息(如果有的话):)
    • 好点,我在循环之前添加了 OERN,因为如果数据不解析,日期转换也会出现错误。
    • 很好的答案,声誉++
    • 进一步我的问题,是否可以获取行号的地址或输出的地址?
    • 是的,您可以创建包含字符串(2011 年 10 月)和范围(在字符串或 Range 对象中)的用户定义类型(结构)。只要键有效,集合就会添加您向其添加的任何值。
    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多