vba 格式功能错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13639833/
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
Error with Format function
提问by uncertaintea
I am having a problem with the Format() function in excel vba. I am trying to alter the formatting of a date formatted cell to change the way it is displayed. However, everytime i invoke Format to do that i get the error: "Compile Error: Wrong number of arguments or invalid property assignment."
我在 Excel vba 中的 Format() 函数有问题。我正在尝试更改日期格式单元格的格式以更改其显示方式。但是,每次我调用 Format 来执行此操作时,都会收到错误消息:“编译错误:参数数量错误或属性分配无效。”
here is the code:
这是代码:
Sub test()
Dim given
given = DateSerial(2012, 10, 11)
dateformat = Format(given, "dd/mm/yy")
MsgBox given & vbCrLf & dateformat
End Sub
This is just a test function and should function on its own and return "11/10/12". This code works on other computers. What could be wrong?
这只是一个测试函数,应该独立运行并返回“11/10/12”。此代码适用于其他计算机。可能有什么问题?
回答by Matthew Whitwam
Had this problem with code I put in a Worksheet_Activate() today and was pulling my hair out. Resolved it by changing Format to VBA.Format
我今天在 Worksheet_Activate() 中放入的代码有这个问题,并且正在拉我的头发。通过将 Format 更改为 VBA.Format 来解决它
So try:
所以尝试:
Sub test()
Dim given
given = DateSerial(2012, 10, 11)
dateformat = VBA.Format(given, "dd/mm/yy")
MsgBox given & vbCrLf & dateformat
End Sub
回答by Rahul Shah
This is because you might also have some Sub
named Format
somewhere else in your project.Hence you get the error.
这是因为您的项目中的其他地方可能还有一些已Sub
命名的名称。因此您会Format
收到错误消息。
回答by bonCodigo
Currently you are declaring your given
variable as a variant by default. Please declare it as Date
data type. And to be safe, make sure you only send a Date
using CDate()
into the Format()
to format as the date style you want.
当前given
,默认情况下您将变量声明为变体。请将其声明为Date
数据类型。为了安全起见,请确保您只将Date
using发送CDate()
到Format()
to 格式作为您想要的日期样式。
Also DateSerial input should be in the following format. Which in your case alright. ;)
DateSerial 输入也应采用以下格式。在你的情况下没问题。;)
DateSerial(CInt(x), CInt(y), CInt(z)
Code snippet:
代码片段:
OPTION EXPLICIT '------------ please add this to your code to begin for better coding
Sub test()
Dim given as Date '-------- define given as Date type
Dim dateformat as Date
given = DateSerial(2012, 10, 11)
dateformat = Format(CDate(given), "dd/mm/yy") '--------- anyway wrap with CDate() to be sure
MsgBox given & vbCrLf & dateformat
End Sub