2017-06-20 341 views
0

我試圖建立一個功能,我很久以前就被阻塞了。如何在VBA中提取字符和數字的通用字符串(模式)?

我想從單元格中的字符串中提取一個像「ABC123」或「AB1234」這樣的子字符串。有一些條件:

  • 它必須是像 「ABC123」 或 「AB1234」,所以3炭和3數字2炭和4數字。即「CDE789」也是這種模式之一。
  • 我們正在尋找的字符串沒有特定的大小。它可能包含或不包含該模式。
  • 如果搜索詞應該在之後或之前有一個空格(那麼只有該模式)。並不是說如果我們在字符串的開頭或結尾,它就不適用。
  • 該函數應返回該特定字符串集(即在除已存在的列以外的列中)。

我試過類似的功能,數組或甚至字典,但我找不到解決方案。例如我試圖循環槽的字符串的LEN,細分6個變量,並檢查一個IF如果前2個字符和最後4個數字。它很重,不適用於大量數據。

我蹩腳的英語還請道歉,不要猶豫,糾正我,我也是她學習這個:)

謝謝!

+1

看正則表達式。 –

+0

RegEX?我對此並不熟悉,但這是一個絕妙的主意!謝謝 ! – Hive

+0

有類似於「A-Z」的做事方式,但我認爲你會因爲這種組合而迷失方向,正則表達式對你來說會更加清潔。 –

回答

0

VBA:計數的字母和數字量與功能

Function AlphaNumeric(pInput As String) As String 
'Updateby20140303 
Dim xRegex As Object 
Dim xMc As Object 
Dim xM As Object 
Dim xOut As String 
Set xRegex = CreateObject("vbscript.regexp") 
xRegex.Global = True 
xRegex.ignorecase = True 
xRegex.Pattern = "[^\w]" 
AlphaNumeric = "" 
If Not xRegex.test(pInput) Then 
    xRegex.Pattern = "(\d+|[a-z]+)" 
    Set xMc = xRegex.Execute(pInput) 
    For Each xM In xMc 
     xOut = xOut & (xM.Length & IIf(IsNumeric(xM), "N", "L")) 
    Next 
    AlphaNumeric = xOut 
End If 
End Function 
+0

如果我在單元格中嘗試它,它只會給我空白單元格。 – Hive

+0

您應該將此代碼放入模塊中。並在A3欄中鍵入如下所示,並將您的值A2列= AlphaNumeric(A2) – JGK

+0

其工作找到我 – JGK

0

編輯:找到了!

感謝您的回答,我實現了這個:

Function GetID(MyRange As Variant) 

    Dim regEx As Object 
    Set regEx = CreateObject("vbscript.regexp") 
    Dim strPattern As String 
    Dim strInput As String 
    Dim strReplace As String 
    Dim strOutput As Object 

    strPattern = "([a-zA-Z]{3})([0-9]{3})" 

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

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

     If regEx.test(strInput) Then 
      Set strOutput = regEx.Execute(MyRange.Value) 
      GetID = regEx.Execute(strInput)(0) 
     Else 
      GetID = "Not matched" 
     End If 
    End If 

End Function 

它的工作原理。但是,有一種情況並非如此: - 如果我的字符多於我的模式。例如ABC123456將返回ABC123。它不應該被考慮在內,只有「ABC123」。即使AABC123被考慮在內,但它不應該。

編輯:它的工作原理是在開頭添加\ B和底:

「\ B([A-ZA-Z] {3})([0-9] {3})\ b 「

非常感謝!

相關問題