2013-06-21 73 views
0

我在單元格P194,P200,P300等中有以下說明。查找並返回值

「截止成本| INV#CAT-02345-BAT-MAT​​07 |線路#00785 |序列#719779 |結算MUG STC4500」

我希望所有的字符INV #直到|INV #之間的字符後和|不是固定的,它有所不同。我正在使用下面的代碼。對P列中的INV#項目而言,該腳本工作正常,但對列P中的非INV#描述不起作用。類似於單元格P12的描述是「GLUCO30 | 57891 ||||| M007Z | 13/15本地主機CDFS | CATT-4FGH548 -20121220 ||| 00013 | FICO56D2F0G0G0 | 「。它將單元格A12中的值打印爲「S-427548-20121220」 爲了更好地理解問題,請在P列中粘貼兩個說明並運行以下代碼。 1)「截止成本| INV#CAT-02345-BAT-MAT​​07 |線#00785 | SEQ#719779 |開賬單MUG STC4500」 2)「GLUCO30 | 57891 ||||| M007Z | 13/15本地主機CDFS | CATT-4FGH548-20121220 ||| 00013 | FICO56D2F0G0G0 |

Sub Invoice() 
    On Error Resume Next 
    Dim RowCtr As Long, MyStart As Long, MyEnd As Long 
    RowCtr = 6 
    While Sheets("Stack").Range("E" & RowCtr).Value <> "" 
     MyStart = WorksheetFunction.Find("#", Sheets("stack").Range("P" & RowCtr).Value, 1) 
     MyEnd = WorksheetFunction.Find("|", Sheets("stack").Range("P" & RowCtr).Value, MyStart) 
     If WorksheetFunction.Find("#", Sheets("stack").Range("P" & RowCtr).Value, 1) > 0 Then 
      Sheets("stack").Range("A" & RowCtr).Value = Mid(Sheets("stack").Range("P" & RowCtr).Value _ 
      , MyStart + 2, MyEnd - MyStart - 2) 
     End If 
     RowCtr = RowCtr + 1 
    Wend 
End Sub 
+0

怎麼辦你知道第二個字符串的哪一部分是你想要的數字嗎? – Zaider

+0

位置字符串diff唯一的缺點是以INV#開始並以|結尾。 –

+0

字符串中是否總是隻有一個#號?如果是的話,你是否嘗試了我在下面發佈的解如果有多個你可以修改它來查找整個'INV#'並從那裏開始工作。 – Zaider

回答

0
Sub changeString(sample As String) 
    ' Find the location of the first # and remove that portion 
    Dim charNum As Integer 
    charNum = InStr(1, sample, "#") 
    sample = Right(sample, Len(sample) - charNum) 

    ' Remove everything from the | till the end 
    charNum = InStr(1, sample, "|") 
    sample = Left(sample, charNum - 1) 
End Sub 
0

另一種方法是用分隔符來分割字符串|或使用正則表達式

Option Explicit 

Sub Method1() 
Dim testString As String 
Dim splitArr() As String 
Dim i As Long 

testString = "Cut-off Cost| INV # CAT-02345-BAT-MAT07| Line # 00785| SEQ # 719779| Billing MUG STC4500" 
splitArr = Split(testString, "|") 
For i = LBound(splitArr, 1) To UBound(splitArr, 1) 
    If InStr(1, splitArr(i), "INV #", vbTextCompare) > 0 Then 
     Debug.Print Trim(Replace(splitArr(i), "INV #", vbNullString)) 
    End If 
Next i 

End Sub 

Sub Method2() 
Dim testString As String 
Dim regex As Object 
Dim regexMatches As Object 

    testString = "Cut-off Cost| INV # CAT-02345-BAT-MAT07| Line # 00785| SEQ # 719779| Billing MUG STC4500" 

    Set regex = CreateObject("vbscript.regexp") 
    With regex 
     .MultiLine = False 
     .Global = False 
     .IgnoreCase = True 
     .Pattern = "INV #[\s\S]+?\|" 
    End With 
    Set regexMatches = regex.Execute(testString) 
    Debug.Print Trim(Replace(Replace(regexMatches(0), "INV #", vbNullString), "|", vbNullString)) 


End Sub