VBA - 找到第二次出现的子串" TL"然后删除所有内容

时间:2015-07-01 18:30:38

标签: excel vba split substring

它的作用:我有一段代码在单元格中找到子串TL,并通过在&#34之后立即添加或删除0来强制其后面的数字为长度为6 ; TL - &#34 ;. (即TL-00072 -> TL-000072TL-034 -> TL-000034TL-000000789 -> TL-000789

我想要它做什么:但是,有时一个单元格中有多个TL值。我需要找出TL是否有第二次出现,如果是,则删除第二次出现及其后的所有内容。

示例:

Start:                           Output:
TL-000789 TL-000187 TL-000773  ->   TL-000789
TL-000689 TL -000787           ->   TL-000689
TL-000982 TL - 980819          ->   TL-000982

这是尝试使用split进行的代码(不正确且无法正常工作)(也许修剪也会起作用?),它会找到TL的第二次出现并删除它之后的所有内容。完整的工作代码。

当前的代码尝试

Dim splitValues As Variant
        If Str(str, "TL" + 1) 'do not know how to get SECOND occurrence
            splitValues = Split(theValue, "TL")
            theValue = splitValues(0)
        End If

工作代码

[将新代码添加到开头](问题顶部的解释)

注意:StartSht是值和代码一样的工作簿。       所有被更改的值都在列" C"

'force length of TL/CT to be 6/4 numbers long, eliminate spaces
    Dim str As String, ret As String, tmp As String, j As Integer, k As Integer
    For k = 2 To StartSht.Range("C2").End(xlDown).Row
        ret = ""
        str = StartSht.Range("C" & k).Value
        'for TL numbers

 ''''''''''''''new code goes here''''''''''''''''''

        If InStr(str, "TL") > 0 Then
            For j = 1 To Len(str)
                tmp = Mid(str, j, 1)
                If IsNumeric(tmp) Then ret = ret + tmp
            Next j
            'force to 6 numbers if too short; add 0s immediately after "TL-"
            For j = Len(ret) + 1 To 6
                ret = "0" & ret
            Next j
            'force to 6 numbers if too long; eliminate 0s immediately after "TL-"
            If Len(ret) > 6 Then
                Debug.Print Len(ret)
                For j = Len(ret) To 7 Step -1
                If Mid(ret, 1, 1) = "0" Then
                    ret = Right(ret, j - 1)
                End If
                Next j
            End If
            'eliminate superfluous spaces around "TL-"
            ret = "TL-" & ret
            StartSht.Range("C" & k).Value = ret
        'for CT numbers
        ElseIf InStr(str, "CT") > 0 Then
            For j = 1 To Len(str)
                tmp = Mid(str, j, 1)
                If IsNumeric(tmp) Then ret = ret + tmp
            Next j
        'force to 4 numbers if too short; add 0s immediately after "CT-"
        For j = Len(ret) + 1 To 4
            ret = "0" & ret
        Next j
        'force to 4 numbers if too long; eliminate 0s immediately after "CT-"
        If Len(ret) > 4 Then
            Debug.Print Len(ret)
            For j = Len(ret) To 5 Step -1
            If Mid(ret, 1, 1) = "0" Then
                ret = Right(ret, j - 1)
        End If
        Next j
    End If
    'eliminate superfluous spaces around "CT-"
    ret = "CT-" & ret
    StartSht.Range("C" & k).Value = ret
 End If
Next k

1 个答案:

答案 0 :(得分:1)

如果找到第二个“TL”,看起来你可以重新定义str。行后:
If InStr(str, "TL") > 0 Then
添加另一个IF声明:
If InStr(3, str, "TL") > 0 Then str = Mid(str, 1, Instr(3, str, "TL") - 2)

然后使用新的str继续使用其余代码。