【问题标题】:Get First And Last Day Of Year获取一年中的第一天和最后一天
【发布时间】:2017-08-19 05:13:26
【问题描述】:

在 VBA 中,我知道您可以使用此语法从日期中减去一年

Dim testdate As String, DateTest As String
testdate= "03/21/2017"
DateTest = Month(testdate) & "/" & Day(testdate) & "/" & Year(testdate) - 1

但是你怎么能找到给定年份的第一天和最后一天呢?例如,让我们使用相同的日期

testdate = "03/21/2017"

并获得以下值

firstdate = "01/01/2017"
lastdate = "12/31/2017"

【问题讨论】:

  • 你可以使用YearEOMonth的组合
  • 我强烈建议您在处理日期时考虑使用 Date 数据类型 - 使用 String 类型会在未来给您带来极大的痛苦,最好现在更改。
  • @YowE3K - 日期正在输入到用户表单文本框中。我可以为此设置日期类型还是必须是字符串,因为它是一个文本框?
  • 它可能需要是文本框中的字符串,但是一旦用户输入,您应该尽快转换为Date。类似于Dim myDate As DateIf Not IsDate(TextBox1.Text) Then MsgBox "Not a date": Exit Sub Else myDate = CDate(TextBox1.Text)。这将允许用户在文本框中输入诸如“2017 年 3 月 27 日”之类的内容,并且 MyDate 将设置为 Date 27/03/2017(或 03/27/2017,如果您按照“mm/dd/yyyy " dates) 然后可用于任何与日期相关的计算。

标签: vba excel date excel-2013


【解决方案1】:

你可以使用DateSerial:

Sub Test()

    Dim dt As Date, firstDay As Date, lastDay As Date

    dt = Date
    firstDay = DateSerial(Year(dt), 1, 1)
    lastDay = DateSerial(Year(dt), 12, 31)

    Debug.Print firstDay
    Debug.Print lastDay

End Sub

【讨论】:

    【解决方案2】:

    如果您总是对年初和年底感兴趣,您可以只使用 1 月 1 日和 12 月 31 日。模仿你的语法:

    Dim testdate As String, DateTest As String
    testdate= "03/21/2017"
    FirstDayOfYear = "1/1/" & Year(testdate)
    LastDayOfYear = "12/31/" & Year(testdate) 
    

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2016-07-18
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多