删除行中的第二个短划线

我有数字在其中的行。 数字看起来像: A-123456A-123456-PA-387785F-489186T-826926-P-2

所以我需要所有带-P-P-2数字来删除它,所以只剩下前半部分: A-123456-P —> A-123456T-826926-P-2 – – > T-826926

我试图通过首先find并replace所有的P* 。 但它留下了-在每个这样的数字剩下的末尾。 我想我不能find*-并且什么也不换,因为第一个破折号会让我留下A 我将如何解决它?

从您的示例中可以明显看出,所有有效值的长度均为8个字符。 因此,要删除右侧不需要的数据,请使用:

 =LEFT(A1,8) 

并抄下来。

如果您有一个完整的电子表格,您可以执行以下操作:

 Option Explicit Function l_find_position(sInputString As String, sFindWhat As String, l_position As Long) As Long Dim l_counter As Long Application.Volatile l_find_position = 0 For l_counter = 1 To l_position l_find_position = InStr(l_find_position + 1, sInputString, sFindWhat) If l_find_position = 0 Then Exit For Next End Function Public Sub TestMe() Dim my_cell As Range For Each my_cell In Selection On Error Resume Next my_cell = Left(my_cell, l_find_position(my_cell.Text, "-", 2) - 1) On Error GoTo 0 Next my_cell End Sub 

很明显,函数l_find_position定位第n个符号的位置,这个函数作为Left()函数的参数给出。 要看到它的工作,只需select您想要剪切的值的范围,并运行TestMe

周六愉快! 🙂

假设文本的长度等于第二个' – '并不总是8个字符,则使用以下公式:

 =LEFT(A1,FIND(CHAR(8),SUBSTITUTE(A1,"-",CHAR(8),2))-1) 

因为它可以用公式完成,在VB中只是使用

 with application.worksheetfunctions result = .left(rng, .find(chr(8), .substitute(rng, "-", chr(8), 2) - 1) end with 

rng成为你有这个值的范围:

 On Error GoTo Next For Each r in rng.Cells If Right(r.Value, 2) = "-P" Then r.Value = Mid(r.Value, 0, Len(r.Value) - 2) End If If Right(r.Value, 4) = "-P-2" Then r.Value = Mid(r.Value, 0, Len(r.Value) - 4) End If Next r On Error GoTo 0