2013-08-29 44 views
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 

回答

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”

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 
0

你可能有原因,它不不起作用,但请查看Split()函数。类似于

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

会在“PP”之后的名称中给出数字答案。

有关Split()的更多信息,请参阅the MSDN documentation

+0

这是假设没有其他文本超出PP#。如果文本类似于“示例OO11 PP222 QQ3456”,那么这种方法将不会提供正确的结果 – tigeravatar

+0

但是,如果文本在PP#之后终止(如提问者示例中所示),那么Split方法将完美工作。 – tigeravatar

+1

上面提供的例子都是“Example PP#”。解决这个问题的方法是双重分割:'PP_Image = Val(Split(Split(MyString,“PP”)(1),“”)(0))' 也就是说,假设数字之后有一个空格。 –

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