2016-11-14 109 views
2

我尝试使用下面的代码,但无法删除逗号。请帮忙。如何删除给定字符串中的最后一个逗号?

Sub removelastcommas() 

    Dim i As Integer, str As String 

    str = Range("A1") 

    For i = Len(str) To 1 
     If Mid(str, i, 1) <> "," Then 
      Exit For 
     End If 
    Next 
    Range("b1") = Left(str, i) 

End Sub 
+2

' = SUBSTITUTE(A1, “”, “”,LEN(A1)-LEN(SUBSTITUTE(A1, “”, “”)))' –

回答

2

另一种选择,使用InStrRev函数(不使用循环)为:

Sub removelastcommas() 

    Dim i As Integer, str As String 
    str = Range("A1") 

    i = InStrRev(str, ",") 
    ' comma found in A1 
    If i > 0 Then 
     Range("B1") = Left(str, i - 1) & Right(str, Len(str) - i) 
    Else ' comma not found in A1 
     Range("B1") = Range("A1") 
    End If 

End Sub 
2

这将从字符串中删除最后一个逗号:

Sub removelastcommas() 
    Dim i As Integer, str As String 
    str = Range("A1") 
     For i = Len(str) To 1 Step -1 
      If Mid(str, i, 1) = "," Then 
       Range("B1").Value = Left(str, i - 1) & Mid(str, i + 1) 
       Exit Sub 
      End If 
     Next i 
End Sub 

enter image description here

相关问题