如何使用 VBA 获取当前年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23479702/
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
How to get current Year Using VBA
提问by sharkantipav
Hi I am using this past thread How To Get The Current Year Using Vba
嗨,我正在使用这个过去的线程如何使用 Vba 获取当前年份
The answer was to use Year(Date)
so I implemented it like this:
答案是使用,Year(Date)
所以我是这样实现的:
Dim a As Integer
a = Year(Date)
But when I tried to use it, I am getting an error
但是当我尝试使用它时,出现错误
Runtime 13 : Type Mismatch
Runtime 13 : Type Mismatch
回答by SQLMason
In Excel VBA, you want to use DATEPART
. Assuming that the data that you're trying to get the year from is valid (which is hard to know from the little information in your question).
在 Excel VBA 中,您希望使用DATEPART
. 假设您试图从中获取年份的数据是有效的(从您问题中的少量信息中很难知道这一点)。
From here:
从这里:
MS EXCEL: DATEPART FUNCTION (VBA)
Learn how to use the Excel DATEPART function with syntax and examples.
DESCRIPTION
The Microsoft Excel DATEPART function returns a specified part of a given date.
SYNTAX
The syntax for the Microsoft Excel DATEPART function is:
DatePart( interval, date, [firstdayofweek], [firstweekofyear] )
MS EXCEL:日期部分功能 (VBA)
了解如何通过语法和示例使用 Excel DATEPART 函数。
描述
Microsoft Excel DATEPART 函数返回给定日期的指定部分。
句法
Microsoft Excel DATEPART 函数的语法是:
DatePart( 间隔, 日期, [firstdayofweek], [firstweekofyear] )
and this specific example:
和这个具体的例子:
DatePart("yyyy", "15/10/2012") would return 2012
DatePart("yyyy", "15/10/2012") 将返回 2012
回答by Brad
I suspect your type mismatch is somewhere else because Year(Date)
is valid. The other option is to use Year(Now)
我怀疑您的类型不匹配在其他地方,因为它Year(Date)
是有效的。另一种选择是使用Year(Now)
I suspect you have declared the variable you are trying to assign to as something weird because VBA will make a lot of bizarre casts for you
我怀疑你已经将你试图分配的变量声明为奇怪的东西,因为 VBA 会为你做很多奇怪的转换
Dim a As String
a = Year(Now) ' "2014"
Dim b As Double
b = Year(Now) '2014
Dim c As Integer
c = Year(Now) '2014
Dim d As Date
d = Year(Date) '#7/6/1905#
Dim e
e = Year(Now) ' 2014 (implicitly cast to integer)
Be sure that you have Option Explicit
set at the top of your module and you compile the code.
确保您已Option Explicit
在模块顶部设置并编译代码。