【问题标题】:Getting specific dates from a date range in VBA从 VBA 中的日期范围获取特定日期
【发布时间】:2017-06-05 09:37:33
【问题描述】:

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

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

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

案例一:

从最后一个可用日期开始,我试图获取 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)

我得到了最后日期的年份,但我又找不到那一年的第一个日期。

任何帮助将不胜感激。

【问题讨论】:

  • 要获得LastRow 完全限定您的代码,请使用LastRow = Worksheets("TIME").Cells(Worksheets("TIME").Rows.Count, "A").End(xlUp).Row
  • 那部分代码由于某种原因已经可以正常工作了。问题在于获得正确的日期。
  • 尝试在VBA中使用内置的日期函数,使用DateAdd,在你的情况下使用day1Y = DateAdd("yyyy", -1, LastRow),它将从变量LastRow中的日期值中减去1年
  • 我不懂“专有”,这如何阻止您使用 WORKDAY 功能?
  • @MarkFitzgerald 我的意思是日期与正常日历不同。 (VBA 使用工作日功能访问的一种)。日期是根据一些预定义的规则给出的,所以缺少一些工作日。

标签: vba excel date


【解决方案1】:

使用循环将第 1 天增加 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

【讨论】:

  • 关于do循环的一个问题:我不需要说明函数值的结果(真或假)吗?
  • 你可以,但它不是必需的,因为它已经是一个布尔值,所以如果你只返回 True 或 False,你不需要(If 同样的事情)! ;)
猜你喜欢
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多