1

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

“截止成本 | INV # CAT-02345-BAT-MAT​​07 | Line # 00785 | SEQ # 719779 | Billing MUG STC4500”

我想要INV #直到之后的所有字符以及和|之间的字符不是固定的,它有所不同。我正在使用下面的代码。该脚本适用于 P 列中的 INV # 项目,但不适用于 P 列中的非 INV # 描述。如单元格 P12 描述为“GLUCO30|57891|||||M007Z|13/15 Local Host CDFS|CATT-4FGH548 -20121220|||00013|FICO56D2F0G0G0|”。它将单元格 A12 中的值打印为“S-427548-20121220”为了更好地理解问题,请将描述粘贴到 P 列并运行以下代码。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|INV #|

    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
4

2 回答 2

1
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
于 2013-06-21T14:40:35.317 回答
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
于 2013-06-21T16:07:47.740 回答