Excel VBA循环遍历一串数字,直到找到一个字母

时间:2016-01-21 15:28:32

标签: string excel vba excel-vba

我在单元格中有一个字符串,让我们说“Client Ref:F123456PassPlus”。 字符串可能在数字前没有字母,数字中可能有符号,字母和数字之间可能有空格。 我只需要将数字作为变量提取。我有代码来做,但它不知道何时停止循环字符串。它应该在有数字或符号以外的东西时停止,但它继续存在。

IsNumber = 1
ref = ""
If branch = "" Then
    e = b
Else
    e = b + 1
End If
f = 1
While IsNumber = 1
    For intpos = 1 To 15
        ref = Mid(x, e, f)
        f = f + 1
        Select Case Asc(ref)
            Case 45 To 57
                IsNumber = 1
            Case Else
                IsNumber = 0
                Exit For
        End Select
    Next
    IsNumber = 0
Wend

之前已经定义了没有定义的任何变量字母,e告诉代码从哪里开始复制,x是包含字符串的单元格。现在,一切正常,它从数字开始并复制它们并将它们构建成一个越来越大的字符串,但它只会在intpos达到15时停止。

3 个答案:

答案 0 :(得分:5)

你试图完成这项任务的方式没有错,但是我无法帮助自己建议正则表达式: - )

此示例将从位于A1的字符串中删除所有非数字,并将结果显示在消息框中。使用的模式是[^0-9]

Sub StripDigits()
    Dim strPattern As String: strPattern = "[^0-9]"
    Dim strReplace As String: strReplace = vbnullstring
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range

    Set Myrange = ActiveSheet.Range("A1")

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

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

        If regEx.test(strInput) Then
            MsgBox (regEx.Replace(strInput, strReplace))
        Else
            MsgBox ("Not matched")
        End If
    End If
End Sub

确保添加对“Microsoft VBScript Regular Expressions 5.5”的引用

有关如何在Excel中使用正则表达式的更多信息,包括循环范围check out this post的示例。

结果:

enter image description here

答案 1 :(得分:3)

我摆脱了Asc检查,并在构建数字&#34;字符串&#34;之前对每个字符添加了一个检查。

IsNumber = 1
ref = ""
If branch = "" Then
    e = b
Else
    e = b + 1
End If
f = 1
While IsNumber = 1
    For intpos = 1 To 15
        char = Mid(x, e + intpos, 1)
        f = f + 1
        If IsNumeric(char) Then
            ref = Mid(x, e, f)
            IsNumber = 1
        Else
            IsNumber = 0
            Exit For
        End If
    Next
    IsNumber = 0
Wend

答案 2 :(得分:2)

这段代码松散地基于你的作品(产生“12345”)。对于大字符串或更复杂的提取需求,我会考虑学习正则表达式COM对象。

Function ExtractNumber(ByVal text As String) As String

  ExtractNumber = ""

  foundnumber = False

  For e = 1 To Len(text)
    ref = Mid(text, e, 1)
        Select Case Asc(ref)
            Case 45 To 57   'this includes - . and /, if you want only digits, should be 48 to 57
                foundnumber = True
                ExtractNumber = ExtractNumber & ref
            Case Else
                If foundnumber = True Then Exit For
        End Select
  Next

End Function