使用VBA从字符串中提取连续数字

时间:2017-03-15 23:16:57

标签: vba excel-vba excel

我写了一个sub,它从单元格A1中的字符串中提取所有数字,并将结果粘贴到单元格A2中。这循环遍历重复该过程的每一行,直到包含字符串的所有单元格都已完成。

但是,我想只提取连续的数字(超过1位数)

例如: 来自这个字符串: string-pattern-7 --- 62378250-stringpattern.html 我只想提取数字 62378250 而不是前面的 7

我应该如何更改代码才能实现此目的?

double sum = 0;
auto it = data.begin();
while(it != data.end() && *it > 2*sum) {
    sum += *it;
    ++it;
}

3 个答案:

答案 0 :(得分:5)

如果您只有一个序列

,请认为这样做
//specifies startIndex according to page comes from
var startIndex = 0;

var jssor_1_options = {
  $StartIndex: startIndex,
  $ArrowNavigatorOptions: {
    $Class: $JssorArrowNavigator$
  },
  $ThumbnailNavigatorOptions: {
    $Class: $JssorThumbnailNavigator$,
    $Cols: 6,
    $SpacingX: 8,
    $SpacingY: 15,
    $Align: 395
  }
};

答案 1 :(得分:1)

考虑:

Public Function onlyDigits(s As String) As String
    Dim L As Long, s2 As String, i As Long, Kapture As Boolean
    Dim CH As String, temp As String

    s2 = s & " "
    L = Len(s2)
    Kapture = False
    temp = ""
    onlyDigits = ""

    For i = 1 To L
        CH = Mid(s2, i, 1)
        If IsNumeric(CH) Then
            temp = temp & CH
            If Len(temp) > 1 Then Kapture = True
        Else
            If Len(temp) < 2 Then
                temp = ""
            Else
                If Kapture Then
                    Exit For
                End If
            End If
        End If
    Next i

    If Kapture Then onlyDigits = temp
End Function

enter image description here

答案 2 :(得分:1)

这与@ Gary&#s; sStudent的优秀答案非常相似,但结构略有不同:

Function ConsecutiveDigits(s As String) As String
    'returns the first substring consisting of 2 or more
    'consecutive digits which is delimited by either a
    'nondigit or the edge of the string
    'returns empty string if no such subtring exists

    Dim i As Long
    Dim c As String
    Dim digits As String

    For i = 1 To Len(s)
        c = Mid(s, i, 1)
        If IsNumeric(c) Then
            digits = digits & c
        Else
            If Len(digits) > 1 Then
                ConsecutiveDigits = digits
                Exit Function
            Else
                digits = "" 'reset
            End If
        End If
    Next i
    'we are at the end of the string -- should we return digits?
    If Len(digits) > 1 Then ConsecutiveDigits = digits
    'else return default empty string

End Function