我的行中有数字。数字看起来像:A-123456
,A-123456-P
,A-387785
,F-489186
,T-826926-P-2
。
所以我最终需要使用-P
或-P-2
的所有数字才能删除它,因此只剩下上半场:A-123456-P
---> A-123456
,T-826926-P-2
----> T-826926
。
我试图通过首先找到并替换所有P*
来做到这一点。但这在每个这样的数字的末尾都留下了-
。我想我不能只找到*-
并一无所有地替换它,因为它会因为第一个破折号而与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-thn符号的位置,并且该符号作为左侧()函数的参数给出。要查看它的工作,只需使用select
带有要剪切和运行TestMe
的值的范围。
有一个愉快的星期六!:)
假设文本长度直到第二' - '并非总是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
让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