VBA – find子string“TL”的第二次出现并删除之后的所有内容

什么作用:我有一段代码可以在单元格中find一个子stringTL,并通过在“TL-”后面加上或者删除0来强制它后面的数字长度为6。 (即, 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 

这是在我一直在使用拆分(不正确,不工作)的代码的尝试(也许修剪也会工作?),会发现TL的第二次发生,并删除它后面的一切。 完整的工作代码下面。

目前在CODE的尝试

 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 

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

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