我想知道今天的月份和年份。
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日,那么我的预期产量是5月和2017年。
答案 0 :(得分:6)
您可能遇到了一些问题,因为您已使用变量名称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)
答案 1 :(得分:4)
更改代码如下:
Option Explicit
Sub automation()
Dim iMonth As Long
Dim iYear As Long
iMonth = month(Date)
iYear = year(Date)
Debug.Print iMonth; iYear
End Sub
Month
和Year
是VBA.DateTime
的函数,不要将它们用于变量名称。
一般情况下,Application.WorksheetFunction
没有与当前日期相关的功能,与VBA.DateTime.Month
或VBA.DateTime.Year
(或至少我没有找到)相比,XL库中没有任何功能
答案 2 :(得分:3)
dim this as date
this = Format(Date(), "yyyy")
this = Format(Date(), "mm")