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

时间:2017-05-15 14:43:03

标签: excel vba

我想知道今天的月份和年份。

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

如果今天的日期是2017年5月15日,那么我的预期产量是5月和2017年。

3 个答案:

答案 0 :(得分:6)

您可能遇到了一些问题,因为您已使用变量名称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函数可用,并且可以在上面的第二个示例中使用。

enter image description here

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

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

答案 1 :(得分:4)

更改代码如下:

Option Explicit

Sub automation()

    Dim iMonth As Long
    Dim iYear As Long

    iMonth = month(Date)
    iYear = year(Date)

    Debug.Print iMonth; iYear

End Sub

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

一般情况下,Application.WorksheetFunction没有与当前日期相关的功能,与VBA.DateTime.MonthVBA.DateTime.Year(或至少我没有找到)相比,XL库中没有任何功能

答案 2 :(得分:3)

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