删除最后一个字符串后缀vba

时间:2017-02-02 08:08:32

标签: excel vba excel-vba

我想知道在删除单元格值中的最后一个字符串值时是否有更有效的方法。

在我的情况下,我需要删除一个后缀,即

TNV1602000014C      //delete suffix C 
117239B             //delete suffix B
MRV117299           //nothing to delete
115365Z             //delete suffix Z        

我尝试过这种方法

lastrow = Cells(Rows.Count, "C").End(xlUp).Row  
Range("E2:E" & lastrow).Formula = "=TRIM(RIGHT(SUBSTITUTE(RC[-1],""A"",REPT("""",LEN(RC[-1]))),LEN(RC[-1])))"

但是因为我需要为整个A-Z做这个。 有什么办法吗?

3 个答案:

答案 0 :(得分:3)

一种稍微简单的公式方法:

lastRow = Cells(Rows.Count, "C").End(xlUp).Row
Range("E2:E" & lastRow).FormulaR1C1 = "=left(RC[-1],LEN(RC[-1])-ISERROR(RIGHT(RC[-1])+0))"

如果您愿意,也可以使用Evaluate来执行此操作。

答案 1 :(得分:1)

下面将循环任何选定的单元格,如果最后一个字符是字母(不是数字或特殊字符),则单元格中的最后一个字符将被删除

 Sub RemoveTrailingLetter()
    Dim c As Range

    'Replace Selection With Your Range
    For Each c In Selection
        'If The Last Character Is A Letter
        If IsLetter(Right(c, 1)) Then
            'Remove The Last Character
            c = Left(c, Len(c) - 1)
        End If
    Next c

End Sub

Function IsLetter(strValue As String) As Boolean
Dim intPos As Integer

    For intPos = 1 To Len(strValue)
        Select Case Asc(Mid(strValue, intPos, 1))
            Case 65 To 90, 97 To 122
                IsLetter = True
            Case Else
                IsLetter = False
                Exit For
        End Select
    Next

End Function

答案 2 :(得分:1)

将其粘贴到您需要使用它的工作簿中的模块中 它将摆脱所有非数字后缀(你可能有多个字符要删除) 您可以直接在Excel中使用它,如=RemoveSuffix(D1)或在VBA循环中

Public Function RemoveSuffix(ByVal StringToClean As String) As String
    Dim i As Integer

    If IsNumeric(Right(StringToClean, 1)) Then
        RemoveSuffix = Trim(StringToClean)
    Else
        i = 1
        Do While Not IsNumeric(Mid(StringToClean, Len(StringToClean) - i, 1))
            i = i + 1
        Loop
        RemoveSuffix = Trim(Left(StringToClean, Len(StringToClean) - i))
    End If
End Function

填写E栏:

lastrow = Cells(Rows.Count, "C").End(xlUp).Row  
Range("E2:E" & lastrow).FormulaR1C1 = "=RemoveSuffix(RC[-1])"

或者覆盖D列:

lastrow = Cells(Rows.Count, "C").End(xlUp).Row
for i = 2 to lastrow  
    Cells(i,4).Value = RemoveSuffix(Cells(i,4).Value)
next i