簡體   English   中英

獲取從今天開始的月份和年份

[英]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 年。

您可能會遇到一些問題,因為您已經使用變量名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函數是可用的,這將在上面的第二個示例中使用。

在此處輸入圖片說明

如果由於某種原因必須保留monthyear變量名稱,則需要完全限定函數調用以避免錯誤:

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

MonthYearVBA.DateTime函數,不要將它們用於變量名。

通常,與 Excel 庫中的VBA.DateTime.MonthVBA.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM