从VBA中的字符串中提取数字

时间:2015-02-27 18:22:56

标签: excel vba parsing excel-vba

我在vba中有包含如下字符串的单元格:

QUANTITY SUPPLY< = DAYS SUPPLY | 30 in 23 DAYS

我通过两个函数发送这些字符串,这两个函数只选取两个数字并将它们解析到适当的单元格中,然后将其余部分丢弃。挑选天数(23)的功能正常但是挑出30的功能却没有。我一直在测试它,它似乎解析了30以及它之前的所有字符串,当我只需要30时。在上面的字符串的情况下,它返回" QUANTITY SUPPLY< = DAYS SUPPLY | 30"什么时候我想要它返回的是30.我已经查看了该功能并找不到问题。任何有关此问题的帮助将不胜感激!

Public Function extractQLlMax(cellRow, cellColumn) As String
    qlm = Cells(cellRow, cellColumn).Value
    extractQLlMax = qlm
    If extractQLinfoBool = "Yes" And Not InStr(1, qlm, "IN") = 0 Then
        If InStr(1, qlm, "QUANTITY SUPPLY") > 0 Then
        pipeIndex = InStr(1, qlm, "|")
        inIndex = InStr(1, qlm, "IN")
        extractQLlMax = Mid(qlm, pipeIndex, inIndex  - pipeIndex)
        End If
        inIndex = InStr(1, qlm, "IN")
        extractQLlMax = Mid(qlm, 1, inIndex - 2)
    ElseIf extractQLinfoBool = "Yes" And Not InStr(1, qlm, "FILL") = 0 Then
        perIndex = InStr(1, qlm, "PER")
        extractQLlMax = Mid(qlm, 1, perIndex - 2)
    End If
End Function

4 个答案:

答案 0 :(得分:3)

您是否考虑在VBA中使用“拆分”功能?如果始终以管道分隔,您可以尝试:

Public Function extractQLlMax(cellRow, cellColumn) As String
    Dim X as Variant
    qlm = Cells(cellRow, cellColumn).Value
    extractQLlMax = qlm

    If extractQLinfoBool = "Yes" And Not InStr(1, qlm, "IN") = 0 Then
        If InStr(1, qlm, "QUANTITY SUPPLY") > 0 Then
        x = Split(qlm,"|")
        extractQLlMax = X(ubound(x))
    ElseIf extractQLinfoBool = "Yes" And Not InStr(1, qlm, "FILL") = 0 Then
        perIndex = InStr(1, qlm, "PER")
        extractQLlMax = Mid(qlm, 1, perIndex - 2)
    End If
End Function

答案 1 :(得分:2)

这将提取字符串中的第一个数字:

Public Function GetNumber(s As String) As Long
    Dim b As Boolean, i As Long, t As String
    b = False
    t = ""
    For i = 1 To Len(s)
        If IsNumeric(Mid(s, i, 1)) Then
            b = True
            t = t & Mid(s, i, 1)
        Else
            If b Then
                GetNumber = CLng(t)
                Exit Function
            End If
        End If
    Next i
End Function

enter image description here

答案 2 :(得分:1)

您可以传递一个可选参数,以区分您想要提取的数字。

Public Function days_supply(blurb As String, Optional i As Long = 1)
    Dim sTMP As String
    sTMP = Trim(Split(blurb, "|")(1))

    If i = 1 Then
        days_supply = CLng(Trim(Left(Replace(sTMP, " ", Space(99)), 99)))
    Else
        sTMP = Trim(Mid(sTMP, InStr(1, LCase(sTMP), " in ", vbTextCompare) + 4, 9))
        days_supply = CLng(Trim(Left(Replace(sTMP, " ", Space(99)), 99)))
    End If
End Function

VBA text parsing Split

B1中的公式是,

=days_supply(A1)

C1中的公式是,

=days_supply(A1,2)

答案 3 :(得分:1)

这是迄今为止提取数字的最短(5行)函数!

Function GetNumbers(str As String, Occur As Long) As Long
Dim regex As Object: Set regex = CreateObject("vbscript.RegExp")
regex.Pattern = "(\d+)"
Regex.Global = True
Set matches = regex.Execute(str)
GetNumbers = matches(Occur)
End Function

参数:

  1. Str是从
  2. 中提取数字的字符串
  3. Occur是该数字的出现(它是从0开始的,所以第一个数字的出现次数为0而不是1,依此类推)