vba 从今天的日期获取月份和年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43982389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the month and year from today's date
提问by UnusualSkill
I am trying to get the month and year for 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
My expected output is 5 for month and 2017 for year if today's date is 15/5/2017.
如果今天的日期是 2017 年 5 月 15 日,我的预期输出是 5 个月和 2017 年。
回答by Vityata
Change in your code like this:
像这样更改您的代码:
Sub CurrentDate()
Dim currentMonth As Long
Dim currentYear As Long
currentMonth = Month(Date)
currentYear = Year(Date)
Debug.Print currentMonth; currentYear
End Sub
Monthand Yearare functions of the VBA.DateTime, do not use them for variable names.
Month和Year是 的函数VBA.DateTime,不要将它们用于变量名。
In general, Application.WorksheetFunctiondoes not have a function, related to current date, in contrast to VBA.DateTime.Monthor VBA.DateTime.Year(or at least I did not find) any in the Excel Library.
一般来说,Application.WorksheetFunction没有与当前日期相关的功能,与Excel 库中的VBA.DateTime.Month或VBA.DateTime.Year(或至少我没有找到)任何功能相反。
回答by David Zemens
You may have some problem because you've shadowed some existing functions Monthand Yearwith your variable names monthand year. So, use different variable names:
您可能会遇到一些问题,因为您隐藏了一些现有函数Month以及Year变量名称month和year. 所以,使用不同的变量名:
Dim m As Integer
Dim y As Integer
And then either:
然后要么:
m = DatePart("m", Date)
y = DatePart("yyyy", Date)
Or:
或者:
m = month(Date)
y = year(Date)
In my Excel 2010 (not tested in 2013) while Monthis a worksheet function, it's not exposed to VBA for some reason. If you want to use the WorksheetFunctioninstance of these, you cantechnically do it using the Application.Evaluatemethod, like so:
在我的 Excel 2010(未在 2013 年测试)中,虽然它Month是一个工作表函数,但由于某种原因它没有暴露给 VBA。如果你想使用这些WorksheetFunction实例,你可以使用该Application.Evaluate方法在技术上做到这一点,如下所示:
m = Evaluate("MONTH(""" & Date & """)")
y = Evaluate("YEAR(""" & Date & """)")
The built-in VBA.DateTime.Monthand VBA.DateTime.Yearfunctions, however, are available and that is what would be used in the second example above.
但是,内置函数VBA.DateTime.Month和VBA.DateTime.Year函数是可用的,这就是上面第二个示例中将使用的。
If you mustfor some reason retain the monthand yearvariable names, then you need to fully qualify the function call to avoid error:
如果你必须出于某些原因保持month和year变量名,那么你需要完全限定的函数调用,以避免错误:
month = VBA.DateTime.Month(Date)
year = VBA.DateTime.Year(Date)
回答by Doug Coats
dim this as date
this = Format(Date(), "yyyy")
this = Format(Date(), "mm")


