2014-05-08 37 views
1

我的VBA代码是取代当前的时间和日期4_17_2014 8_09_00 PM格式获取类型不匹配错误替换VBA函数

但我正在逐渐类型不匹配错误运行下面的VBA代码,而

Function Current_Date_Time_Stamp() 

Dim CurrTime As Date 

CurrTime = Now 
MsgBox Now 
CurrTime = Replace(CurrTime, "-", "_") 
MsgBox CurrTime 
CurrTime = Replace(CurrTime, ":", "_") 
Current_Date_Time_Stamp = CurrTime 

End Function 

任何人可以帮助我,为什么我得到错误

+0

在哪一行,你得到的错误? –

+1

替换在字符串上运行,并且您给它一个日期。如果您想要日期值的特定表示,请尝试查看Format()。 –

+0

蒂姆威廉姆斯,我在第5行发生错误 – user3591858

回答

1

由于@Tim威廉姆斯在评论中提到,Replace仅适用于变量,但CurrTime日期(实际上,日期变量不存储日期的格式,但仅限日期本身。格式为时显示日期取决于您的单元格的区域设置和数字格式)。

但是你可以使用函数像这样的一行代码:

Function Current_Date_Time_Stamp() 
    Current_Date_Time_Stamp = Format(Now, "mm_dd_yyyy h_mm_ss AM/PM;@") 
End Function 
+0

感谢您的回复,它帮助我很多 – user3591858