我已经在excel VBA中创建了用户定义的函数:
Public Function RegExpReplace(Text As String, Pattern As String, replaceVar As String, Optional Glob As Boolean = False, Optional IgnoreCase As Boolean = False, Optional Multiline As Boolean = False) As Variant
On Error GoTo ErrHandl
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = Pattern
regex.Global = Glob
regex.IgnoreCase = IgnoreCase
regex.Multiline = Multiline
RegExpReplace = CVar(regex.Replace(Text, replaceVar))
MsgBox RegExpReplace
ErrHandl:
RegExpReplace = CVErr(xlErrValue)
End Function
但是当我尝试从工作表中调用它时,出现了 #VALUE!错误:
MsgBox显示正确的结果:
答案 0 :(得分:1)
那样更改代码
Public Function RegExpReplace(Text As String, Pattern As String, replaceVar As String, Optional Glob As Boolean = False, Optional IgnoreCase As Boolean = False, Optional Multiline As Boolean = False) As Variant
On Error GoTo ErrHandl
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = Pattern
regex.Global = Glob
regex.IgnoreCase = IgnoreCase
regex.Multiline = Multiline
RegExpReplace = CVar(regex.Replace(Text, replaceVar))
MsgBox RegExpReplace
Exit Function
ErrHandl:
RegExpReplace = CVErr(xlErrValue)
End Function
在没有错误的情况下,您忘记退出函数,因此即使没有错误,也执行了行RegExpReplace = CVErr(xlErrValue)
,为您提供 #Value 。