繁体   English   中英

获取从今天开始的月份和年份

[英]Get the month and year from today's date

我正在尝试获取今天日期的月份和年份。

Sub automation()

Dim wsheet As Worksheet
Dim month As Integer
Dim year As Integer

Set wsheet = Application.Workbooks("try").Worksheets("try")

month = Application.WorksheetFunction.month(Date)

year = Application.WorksheetFunction.year(Date)

End Sub

如果今天的日期是 15/5/2017,我的预期输出是 5 个月和 2017 年。

您可能会遇到一些问题,因为您已经使用变量名monthyear隐藏了一些现有函数MonthYear 所以,使用不同的变量名:

Dim m As Integer
Dim y As Integer

然后要么:

m = DatePart("m", Date)
y = DatePart("yyyy", Date)

或者:

m = month(Date)
y = year(Date)

在我的 Excel 2010(未在 2013 年测试)中,虽然Month是一个工作表函数,但由于某种原因它没有暴露给 VBA。 如果您想使用这些WorksheetFunction实例,您可以使用Application.Evaluate方法在技术上做到这一点,如下所示:

m = Evaluate("MONTH(""" & Date & """)")
y = Evaluate("YEAR(""" & Date & """)")

但是,内置的VBA.DateTime.MonthVBA.DateTime.Year函数是可用的,这将在上面的第二个示例中使用。

在此处输入图片说明

如果由于某种原因必须保留monthyear变量名称,则需要完全限定函数调用以避免错误:

month = VBA.DateTime.Month(Date)
year = VBA.DateTime.Year(Date)

像这样更改您的代码:

Sub CurrentDate()

    Dim currentMonth As Long
    Dim currentYear As Long

    currentMonth = Month(Date)
    currentYear = Year(Date)

    Debug.Print currentMonth; currentYear

End Sub

MonthYearVBA.DateTime函数,不要将它们用于变量名。

通常,与 Excel 库中的VBA.DateTime.MonthVBA.DateTime.Year (或至少我没有找到)相比, Application.WorksheetFunction没有与当前日期相关的函数。

dim this as date
this = Format(Date(), "yyyy") 
this = Format(Date(), "mm")

回答晚了,但我想参考微软自己页面上的 VBA 文档。

从日期获取月份:

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/month-function

示例片段:

Dim MyDate, MyMonth
MyDate = #February 12, 1969#    ' Assign a date.
MyMonth = Month(MyDate)    ' MyMonth contains 2.

从日期获取年份:

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/year-function

示例片段:

Dim MyDate, MyYear
MyDate = #February 12, 1969#    ' Assign a date.
MyYear = Year(MyDate)    ' MyYear contains 1969.

我喜欢这些答案,但我需要一个包含格式的月份和年份的答案(我的用例是一名会计师)。 这是我的解决方案:

Dim today As Date
today = Date ' Get the current date

Dim period As String
period = Format(today, "MM/YYYY") ' Convert the date to MM/YYYY 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM