在vba中的replace函数中获取类型不匹配错误 [英] Getting type mismatch error in replace function in vba

查看:392
本文介绍了在vba中的replace函数中获取类型不匹配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的vba代码是将当前时间和日期替换为4_17_2014 8_09_00 PM格式

My vba code is to replace current time and date to 4_17_2014 8_09_00 PM format

但是,在VBA代码下运行时,我遇到类型不匹配错误

But i am getting type mismatch error while running below VBA code

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

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

Can anybody help me why i am getting error

推荐答案

正如@Tim Williams在评论中提到的,替换 em> string 变量,但 CurrTime date (实际上,日期变量不存储格式的日期,但仅限日期本身。显示日期的格式取决于您的单元格的区域设置和数字格式。

As @Tim Williams mentioned in comments, Replace works only with string variables, but CurrTime is date (actually, date variables doesn't store format of date, but only date itself. Format when displaying date depends on regional settings and number format of your cell).

但是,您可以使用功能与单李这样的代码:

However you can use function with single line of code like this:

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

这篇关于在vba中的replace函数中获取类型不匹配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆