2016-02-04 18 views
3

我在网上发现了很多东西,告诉我如何创建函数以及如何实现它,但没有什么能帮助我找出为什么它不接受函数的名字。正则表达式产生#NAME? UDF中的错误

我打开开发人员的Visual Basic部分。我输入了我的代码,我认为是吗? Ctrl + S只能让我保存表格,而不是代码。

我的代码的目的是取一个字符串,并删除前7个字符,其中之一将是一个;以下6个将是随机数字。我还有更多的修复工作要做,比如从最后删除4个随机字符,但我想先测试一下。

这里是我的代码:

Function simpleCellRegex(Myrange As Range) As String 
Dim regEx As New RegExp 
Dim strPattern As String 
Dim strInput As String 
Dim strReplace As String 
Dim strOutput As String 


strPattern = "^[;][0-9]{6}" 

If strPattern <> "" Then 
    strInput = Myrange.Value 
    strReplace = "" 

    With regEx 
     .Global = True 
     .MultiLine = True 
     .IgnoreCase = False 
     .Pattern = strPattern 
    End With 

    If regEx.test(strInput) Then 
     simpleCellRegex = regEx.Replace(strInput, strReplace) 
    Else 
     simpleCellRegex = "Not matched" 
    End If 
End If 
End Function 

我不知道如果有,我很想念,让Excel来接受我的码的步骤。

感谢您的帮助!

+0

您是否试图从另一个宏调用您的函数传递一个范围?这可能有助于调试。如果您的功能不受支持,则很可能包含错误。 – Fuzzzzel

+2

您是否将模块添加到工作簿并在其中定义该功能?在工作表中定义的函数不起作用 –

+1

@Fuzzzzel我实际上从本网站高度投票的线程中获取了整个函数 - http://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in -Microsoft-Excel的两种功能于细胞和循环。 – Ryan

回答

1

看看这个话题。您很可能错过了添加对Microsoft VBScript Regular Expressions 5.5的引用。您在“如何使用”找到它:

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

+1

没有引用会导致不同的错误。 –

+0

这是不正确的。我在Excel中测试了它。实际上,如果函数没有错误(并且没有引用“RegExp”将不会被识别),它将不能被调用,并且由此将显示#NAME? – Fuzzzzel

+1

如果放置在一个常规模块中,没有引用集,那么它返回一个'用户定义类型未定义'的编译错误。当然,如果你错误地把它放在一个sheet模块中,那么你会得到#NAME!错误。 –

1

我已经重新切割下面的代码清理变量,并使用后期绑定

还能够为用户当前的代码犯规应试不止一个细胞进入该范围。

Function simpleCellRegex(Myrange As Range) As String 
Dim regEx As Object 
Dim strPattern As String 
Dim strReplace As String 

Set regEx = CreateObject("vbscript,regexp") 

strPattern = "^[;][0-9]{6}" 
If Len(strPattern) = 0 Then Exit Sub 

simpleCellRegex = "Not matched" 
strReplace = vbNullString 

With regEx 
    .Global = True 
    .MultiLine = True 
    .IgnoreCase = False 
    .Pattern = strPattern 
    If .test(Myrange) Then simpleCellRegex = .Replace(Myrange.Value2, strReplace) 
End With 

End Function