Excel 获取从今天开始的月份和年份';日期
我想知道今天日期的月份和年份Excel 获取从今天开始的月份和年份';日期,excel,vba,Excel,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.ye
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日,我的预期输出是2017年5月5日。您的代码更改如下:
dim this as date
this = Format(Date(), "yyyy")
this = Format(Date(), "mm")
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
的函数,不要将它们用于变量名
通常,
Application.WorksheetFunction
没有与当前日期相关的函数,而不是VBA.DateTime.Month
或VBA.DateTime.Year
(或者至少我没有找到)Excel库中的任何函数。您可能会遇到一些问题,因为您使用变量名Month
和Year
隐藏了一些现有函数Month
和Year
。因此,请使用不同的变量名:
Dim m As Integer
Dim y As Integer
然后:
m = DatePart("m", Date)
y = DatePart("yyyy", Date)
或:
在我的Excel 2010(2013年未测试)中,Month
是一个工作表函数,但由于某些原因,它没有暴露于VBA。如果要使用这些函数的工作表函数
实例,从技术上讲,可以使用应用程序来执行。请评估方法,如下所示:
m = Evaluate("MONTH(""" & Date & """)")
y = Evaluate("YEAR(""" & Date & """)")
但是,内置的VBA.DateTime.Month
和VBA.DateTime.Year
函数是可用的,这就是上面第二个示例中使用的功能
如果出于某种原因必须保留月
和年
变量名,则需要完全限定函数调用以避免错误:
month = VBA.DateTime.Month(Date)
year = VBA.DateTime.Year(Date)
Month
和Year
是VBA.DateTime
模块中的函数,未保留;-)完全限定名实际上是VBA.DateTime.Month
;-)为什么你们要比我聪明
month = VBA.DateTime.Month(Date)
year = VBA.DateTime.Year(Date)