如何在字符串中提取三个数字字符?

时间:2013-08-29 18:02:58

标签: string vba

我在Excel中有一长串名称,其中包含“PP”后跟一个数字。例如PP10P101.

我想在'PP'之后提取数字。我尝试过以下代码,但它似乎只能用于PP99,“PP”之后的三个数字字符无法正常读取。

For n = 1 To MyCount

    If Mid(MyString, n, 2) = "PP" Then

        If IsNumeric(Mid(MyString, n + 2, 1)) Then

            PP_Image = Mid(MyString, n + 1, 3)

        End If
    End If
Next n


If IsNumeric(Mid(PP_Image, 2, 2)) Then

    PP_Image = Mid(PP_Image, 2, 2)

Else: IsNumeric (Mid(PP_Image, 2, 1))

    PP_Image = Mid(PP_Image, 2, 1)

End If

4 个答案:

答案 0 :(得分:0)

检查您的指数。如果Mid(MyString, n, 2) = "PP"IsNumeric(Mid(MyString, n + 2, 1)) = True,则Mid(MyString, n + 1, 3)将为您提供“Pxx”,并留下最后一个号码。然后,这将使您以后的检查和转换关闭。将PP_Image的分配更改为

PP_Image = Mid(MyString, n + 2, 3)

注意n + 2,以便与之前的“PP”搜索保持一致

答案 1 :(得分:0)

也许

Function PP_Image(ByVal MyString As String) As Double

    Dim lPosition As Long

    lPosition = InStr(1, MyString, "PP", vbTextCompare)
    Select Case (lPosition > 0)
        Case True:  PP_Image = --Trim(Left(Replace(MyString, " ", String(99, " "), lPosition + 2), 99))
        Case Else:  PP_Image = 0
    End Select

End Function

Sub tst()

    Dim varString As Variant

    For Each varString In Array("Example PP10", "Example PP101")
        MsgBox PP_Image(varString) ' => 10, 101
    Next varString

End Sub

答案 2 :(得分:0)

您可能有理由说它不起作用,但请查看Split()函数。像

这样的东西
PP_Image = Val(Split(MyString, "PP")(1))

将在“PP”之后给出名称中任何内容的数字答案。

有关Split()的详细信息,请参阅the MSDN documentation

答案 3 :(得分:0)

Sub Tester()
    Debug.Print PPMatch("sdhgs sh s PP22 ggg")
    Debug.Print PPMatch("sdhgs sh s PPs66 ggg")
    Debug.Print PPMatch("sdhgs sh s PP555555 ggg")
    Debug.Print PPMatch("sdhgs sh s PP0 ggg")    
End Sub


Function PPMatch(txt As String)
Dim re As Object, matches, match

    Set re = CreateObject("vbscript.regexp")
    re.Pattern = "PP(\d+)"
    re.ignorecase = False
    re.Global = True
    Set matches = re.Execute(txt)
    If matches.Count > 0 Then
        PPMatch = matches(0).submatches(0)
    Else
        PPMatch = ""
    End If
End Function