2017-05-15 579 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 –

相關問題