2017-05-15 580 views
1

我试图获得今天的VBA日期的年份和月份,我曾尝试和下面是我的代码: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
dim this as date 
this = Format(Date(), "yyyy") 
this = Format(Date(), "mm") 
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资源库中

+1

'Month'和'年'是'VBA.DateTime'模块中的函数,不保留;-) –

+0

@ Mat'sMug - 谢谢,编辑。 – Vityata

5

你可能有一些问题,因为你已经遮蔽了一些现有的其他功能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) 
+3

*完全*限定名称实际上是'VBA.DateTime.Month' ;-) –

+2

确实。虽然两者都有效。我会更新:) –

+0

为什么你们必须比我聪明O_o –

相关问题