2013-03-12 30 views
1

,我有以下形状的字符串:如何提取号码组从一个字符串在VBA

RRP 90 AVE DE GAULLE 92800 PUTEAUX 0109781431-0149012126 

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

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

我已经找到了如何从字符串中去除的字符掉: How to find numbers from a string?

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

你能告诉我到代码的函数或该位可以帮助我呢?

+0

正则表达式... – 2013-03-12 18:52:35

+0

你需要在结果中的数字组之间进行一些分离吗?是“909280001097814310149012126”还是您需要“90 92800 0109781431 0149012126”? – barrowc 2013-03-12 23:36:30

+0

我已更新我的问题 – Chipsgoumerde 2013-03-13 09:02:07

回答

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 
+0

这一个没有返回任何东西,我正在阅读关于正则表达式来理解为什么。 – Chipsgoumerde 2013-03-13 10:31:29

+0

使用此代码'RRP 90 AVE DE GAULLE 92800 PUTEAUX 0109781431-0149012126'通过键入'= numericonly(B1)'返回'90 92800 01097814310149012126',其中文本字符串在B1中 – scott 2013-03-13 13:26:09

+0

谢谢,这样,它就可以工作。 。但是,最后一个字符串需要分离的地方连字符是... – Chipsgoumerde 2013-03-13 13:34:28

1

试试下面的代码:

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 
+0

这一个很好,但数字都粘在一起 – Chipsgoumerde 2013-03-13 10:30:53

+0

@Chipsgoumerde你想如何显示数字?你想添加它们吗? – 2013-03-13 10:53:37

+0

nop,它不是用于计算,而是在另一个工作表/列中搜索数字。澄清:我将检查每组数字:如果它是9位数字>在列A中搜索/如果它是10位数字在列B中搜索它 – Chipsgoumerde 2013-03-13 11:04:46

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 

我得到的输出是

我运行代码后。

相关问题