如何从vba中的字符串中提取数字组

时间:2013-03-12 18:41:36

标签: excel vba

我有一个以下形状的字符串:

RRP 90 AVE DE GAULLE 92800 PUTEAUX 0109781431-0149012126

这些数字可能被其他字符分隔而不是连字符(例如空格)。我知道如何用len()来区分它们。

我需要单独存储每个数字串(例如,在数组中),以便我可以用len()区分它们然后使用它们。

我找到了如何从字符串中剥离字符: How to find numbers from a string?

但它不适合我的问题...

你能指导我一个能帮我解决这个问题的函数或代码吗?

4 个答案:

答案 0 :(得分:2)

尝试以下代码:

Function parseNum(strSearch As String) As String

   ' Dim strSearch As String
    'strSearch = "RRP 90 AVE DE GAULLE 92800 PUTEAUX 0109781431-0149012126"

    Dim i As Integer, tempVal As String
    For i = 1 To Len(strSearch)
        If IsNumeric(Mid(strSearch, i, 1)) Then
            tempVal = tempVal + Mid(strSearch, i, 1)
        End If
    Next

    parseNum = tempVal
End Function

答案 1 :(得分:2)

这将比循环

运行得快得多
Public Function NumericOnly(s As String) As String
    Dim s2 As String
    Dim replace_hyphen As String
    replace_hyphen = " "
    Static re As RegExp
    If re Is Nothing Then Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    re.Pattern = "[^0-9 -]" 'includes space, if you want to exclude space "[^0-9]"
    s2 = re.Replace(s, vbNullString)
    re.Pattern = "[^0-9 ]"
    NumericOnly = re.Replace(s2, replace_hyphen)
End Function

答案 2 :(得分:0)

所以我意识到这是很久以前的...但我在网上寻找类似的解决方案。

我编程技巧的一些历史记录(原文如此):我从Python开始,使用Python,我有一个名为List的方便工具。 VBA没有这个,所以我留下的东西是我可以在下面叫sample的变量中输入的内容,即sample = [1,4,5]

回到小代码。我这样做了holder只包含数字组,就像你指定它们应该如何分组一样。

Dim count, count1 As Integer
Dim holder As String
Dim sample, smallSample As String


count = 0
count1 = 1
sample = "1ab33 efa 123 adfije-23423 123124-23423"
holder = ""
Do While count <> Len(sample)
    smallSample = Left(sample, 1)
    If smallSample = "0" Or smallSample = "1" Or smallSample = "2" Or smallSample = "3" Or smallSample = "4" Or smallSample = "5" Or smallSample = "6" Or smallSample = "7" Or smallSample = "8" Or smallSample = "9" Then
        holder = holder & smallSample
    Else
        If holder <> "" Then
            Cells(count1,1) = holder
            count1 = count1 + 1
        End If
        holder = ""
    End If
    sample = Right(sample, Len(sample) - 1)

Loop

我得到的输出是

  

1

     

33

     

123

     

23423

     

123124

我运行代码后。

答案 3 :(得分:-1)

如果您在编译时遇到错误&#34;问题,则用户定义的类型未定义&#34;使用@Scotts时启用正则表达式选项,如步骤1和2所示:How to Use/Enable (RegExp object) Regular Expression using VBA (MACRO) in word(也可在Excel中使用)

P.S。 Scotts Solution对我来说效果很好。

相关问题