[英]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 年。
您可能會遇到一些問題,因為您已經使用變量名month
和year
隱藏了一些現有函數Month
和Year
。 所以,使用不同的變量名:
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.Month
和VBA.DateTime.Year
函數是可用的,這將在上面的第二個示例中使用。
如果由於某種原因必須保留month
和year
變量名稱,則需要完全限定函數調用以避免錯誤:
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
Month
和Year
是VBA.DateTime
函數,不要將它們用於變量名。
通常,與 Excel 庫中的VBA.DateTime.Month
或VBA.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.