如何在VBA中查找两个字符之间的数字

时间:2015-01-13 02:02:35

标签: vba

例如,我有一个读取"IRS150Sup2500Vup"的字符串。它也可以是"IRS250Sdown1250Vdown"

我希望提取两个S之间的数字。因此对于第一种情况,它将是150和第二种情况,它是250.数字不总是3位数。它可能会有所不同。

我尝试过:

Dim pos As Integer
Dim pos1 As Integer

pos = InStr("IRS150Sup2500Vup", "S")
pos1 = InStrRev("IRS250Sdown1250Vdown","S")

在此之后,我被困在如何获取数字。

需要一些指导如何执行此操作。

3 个答案:

答案 0 :(得分:4)

正如我建议here,最简单的方法是使用正则表达式。

Sub Test()
Dim r As VBScript_RegExp_55.RegExp
Dim sPattern As String, myString As String
Dim mc As VBScript_RegExp_55.MatchCollection, m As VBScript_RegExp_55.Match

myString = "IRS150Sup2500Vup"
sPattern = "\d+" 'searches for numbers 
Set r = New VBScript_RegExp_55.RegExp
r.Pattern = sPattern

Set mc = r.Execute(myString)
For Each m In mc ' Iterate Matches collection.
    MsgBox "number: '" & m.Value & "' founded at: " & m.FirstIndex & " length: " & m.Length
Next

End Sub

答案 1 :(得分:3)

这是一个选项:

Public Sub Test4()

    Dim pos As Integer
    Dim pos1 As Integer
    Dim strOrig As String
    Dim strString As String

    strOrig = "IRS150Sup2500Vup"

    pos = InStr(1, strOrig, "S") + 1
    pos1 = InStr(pos, strOrig, "S")
    strString = Mid(strOrig, pos, pos1 - pos)

    MsgBox strString

End Sub

答案 2 :(得分:-1)

尝试使用此功能:

pos = Mid("IRS150Sup2500Vup", 4, 6)