查找并返回值

时间:2013-06-21 13:43:56

标签: vba find return

我在单元格P194,P200,P300等中有以下描述。

“截止成本| INV#CAT-02345-BAT-MAT​​07 | Line#00785 | SEQ#719779 | Billing 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中粘贴描述并运行以下代码。 Cloumn P中的描述 1)“截止成本| INV#CAT-02345-BAT-MAT​​07 | Line#00785 | SEQ#719779 | Billing 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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