2016-03-10 162 views
5

我一直在玩VBA中的date,並且無法獲得當前月份。通過以下測試得出當前年份和日期似乎非常簡單:Excel VBA當前獲得月份

MsgBox Year(Date) 
MsgBox Day(Date) 
MsgBox Year(Now) 
MsgBox Day(Now) 

作爲一些簡單的例子。

但是,如何將當前月份顯示爲數字(1,2等)或全名?我可以在單元格中使用TODAY(),並將其轉換爲類似於CurrentMonth = MonthName(Month(Sheet1.Range("A1")))之類的VBA。但我希望能夠直接在VBA for Excel中執行此操作。

+2

'月(現在)'不起作用?它應該返回3 –

+0

不,不是因爲某些原因,所以我的困惑。 –

+0

'?月(日期),月(現在)'將返回'3,3' - 你看到了什麼? –

回答

16

嘗試,

debug.print Format(Date, "mmm")  'Mar 
debug.print Format(Date, "mmmm")  'March 
debug.print Int(Format(Date, "m")) '3 
debug.print Int(Format(Date, "mm")) '03 
2
Month(Now) 

返回與當前月份相關的索引號。下面

Jeeped的代碼是最緊湊的,但給你的指標是如何工作的想法,下面的代碼將返回基於索引月份名稱返回:

Dim months(11) As String 
months(0) = "Jan" 
months(1) = "Feb" 
months(2) = "Mar" 
months(3) = "Apr" 
months(4) = "May" 
months(5) = "Jun" 
months(6) = "Jul" 
months(7) = "Aug" 
months(8) = "Sep" 
months(9) = "Oct" 
months(10) = "Nov" 
months(11) = "Dec" 

Dim nowMonth As Integer 
nowMonth = Month(Now) 

For i = 0 To 11 
    If nowMonth = (i + 1) Then 
    MsgBox (months(i)) 
    End If 
Next 
+0

@ScottCraner我發佈了一個快速的答案,並且正在研究我剛發佈的更完整的代碼。無需投票正確答案,因爲您不喜歡發佈時間。 –

+0

@ScottCraner;) –

相關問題