2016-11-14 103 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

相關問題