从VBA中的string中提取数字

我在vba中包含像这样的string的单元格:

数量供应<=天供应| 23天23

我通过两个函数发送这些string,只是挑出这两个数字,并将它们parsing成适当的单元格,然后剩下的就剩下了。 挑出天数(23)的function工作正常但是挑出30的function不是。 我一直在testing它,它似乎是parsing出30以及它之前的整个string,当我想要的是30.在上面的string的情况下,它返回“QUANTITY SUPPLY <= DAYS SUPPLY | 30 “当我想要它返回的是30。我已经看了function,找不到问题。 任何帮助这个问题将不胜感激!

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 

你有没有考虑在VBA中使用“Split”function? 如果它总是用pipe道分隔,你可以尝试:

 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 

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

 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 

在这里输入图像说明

你可能传递一个可选参数来区分你想要拉的数字。

 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文本解析Split

B1中的公式是,

 =days_supply(A1) 

C1中的公式是,

 =days_supply(A1,2) 

这是迄今为止提取数字的最短(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是从中提取数字的string
  2. Occur是这个数字的出现(它是基于0的,所以第一个数字的出现次数是0而不是1,依此类推)