2016-11-26 42 views
2

我有包含数字的行。数字看起来像:A-123456,A-123456-P,A-387785,F-489186,T-826926-P-2删除行中的第二个破折号

所以我需要与-P-P-2所有数字在年底将其删除,所以才有了上半年依然存在:A-123456-P --->A-123456T-826926-P-2 --->T-826926

我试图通过首先查找并替换全部P*来完成此操作。但是在剩下的每一个这样的号码末尾,我留下了-。我想我不能只找到*-并用什么都不换,因为第一个破折号会让我跟A一起。我将如何解决它?

回答

3

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

=LEFT(A1,8) 

并复制下来。

1

如果您有与整个电子表格,你可以做到以下几点:

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

周六愉快! :)

0

允许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 
1

假设文本的长度,直到第二“ - ”并不总是8个字符,然后使用以下公式:

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

因为它可以用公式完成,在vba中只需使用

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