首页 文章

从VBA中的日期范围获取特定日期

提问于
浏览
1

我有一张工作表在A栏中有一系列日期 . 我已经找到了获得最后一行的方法:

LastRow = Worksheets("TIME").Cells(Rows.Count, "A").End(xlUp).Row

现在我正在尝试获取具体日期 . 该范围不包含周末,但由于日期是专有的,我无法使用WorkDay函数来查找我需要的内容 .

案例1:

从可用的最后日期开始,我试图获取1年前的日期(如果日期不可用,请选择下一个可用的日期) .

我在这里做的是使用日期函数并减去1年..

day1Y = date(year(LastRow)-1,month(LastRow),day(LastRow))

为了匹配,我将日期范围转换为数组,并使用函数确定它是否在数组中 . 如果是,那就去吧,但如果不是,我不知道如何获得下一个 .

Dim DateArray() as Variant
Dim WantedDate1 as date
Dim WantedDate2 as date
DateArray() = Worksheets("TIME").Range("A2:A" & LastRow).Value

If IsInArray(day1Y) = True then
WantedDate1 = .Cells(1,LastRow).Value
End if

案例2:

从上一个可用日期开始,我试图获得同一年的第一个日期(如果上次日期是2015年8月10日,则根据该范围内的可用日期获得2015年的第一个可用日期) .

WantedDate2 = Year(.Cells(1,LastRow).Value)

我得到了最后一次的那一年,但是再一次,我找不到那一年的第一个日期 .

任何帮助将深表感谢 .

1 回答

  • 3

    使用循环将天数增加1并测试它是否是随时可用的数组:

    Option Explicit
    
    Sub DGMS89()
        Dim wsT As Worksheet
        Dim LastRow As Double
        Dim DateArray() As Variant
        Dim LastDate As Date
        Dim Day1y As Date
        Dim WantedDate1 As Date
        Dim WantedDate2 As Date
    
        Set wsT = ThisWorkbook.Sheets("TIME")
        LastRow = wsT.Cells(wsT.Rows.Count, "A").End(xlUp).Row
        DateArray() = wsT.Range("A2:A" & LastRow).Value
    
        LastDate = DateArray(UBound(DateArray, 1))
        Day1y = DateAdd("yyyy", -1, LastDate)
    
        WantedDate1 = Day1y
        If IsInArray(WantedDate1) Then
        Else
            Do While Not IsInArray(WantedDate1)
                WantedDate1 = DateAdd("d", 1, WantedDate1)
            Loop
        End If
    
        WantedDate2 = DateSerial(year(LastDate), 1, 1)
        Do While Not IsInArray(WantedDate2)
            WantedDate2 = DateAdd("d", 1, WantedDate2)
        Loop
    
    End Sub
    

相关问题