2016-02-04 97 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