2

我在 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

4 回答 4

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
于 2013-08-29T21:01:32.293 回答
0

您可能有它不起作用的原因,但请查看 Split() 函数。就像是

PP_Image = Val(Split(MyString, "PP")(1))

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

有关 Split() 的更多信息,请参阅MSDN 文档

于 2013-08-29T18:36:49.313 回答
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
于 2013-08-29T18:27:48.647 回答
0

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

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

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

于 2013-08-29T18:13:43.450 回答