修剪字符串中字符的第二到最后一个实例

时间:2019-09-17 16:46:16

标签: excel vba

我正在尝试使用MID修剪字符串,以便删除/倒数第二个之后的所有内容。

mom/dad/brother/sister/me/   to     mom/dad/brother/sister/
thor/ironman/thanos/         to     thor/ironman/

我正在尝试使用MidLeftInStrRev的组合,但可能会对此有所考虑。我的东西在下面,什么也没发生。...

For i = 2 to LR
     dq.Range("U" & i) = Mid(dq.Range("U" & i), 1, InStrRev(Mid(dq.Range("U" & i), 1, Len(dq.Range("U" & i) - 1)), "/", -1, vbTextCompare))
Next i

我猜问题出在InStrRev

3 个答案:

答案 0 :(得分:4)

使用拆分

    For i = 2 To LR
        Dim spltStr() As String
        'Split the string on the "\"
        spltStr = Split(dq.Range("U" & i), "/")
        'Remove the last two
        ReDim Preserve spltStr(UBound(spltStr) - 2)
        'Join the array with "/" as the delimiter and add the extra on the back
        dq.Range("U" & i).Value = Join(spltStr, "/") & "/"
    Next i

之前:

enter image description here

之后:

enter image description here

答案 1 :(得分:1)

@Craners解决方案也可以使用,并且速度更快


我的方法有问题:

  1. Len(Range - 1)无效。这应该是Len(Range) - 1
  2. 已删除vbTextCompare

下面的命令返回正确的结果,以修剪字符串直到直到第二个字符为止。

Mid(dq.Range("U" & i), 1, InStrRev(Mid(dq.Range("U" & i), 1, Len(dq.Range("U" & i)) - 1), "/", -1))

答案 2 :(得分:0)

这是一个很好的小功能,可以解决问题

Option Explicit

Sub TestStrip()

    Debug.Print Strip("mom/dad/brother/sister/me/", "/", 2)
    Debug.Print Strip("thor/ironman/thanos/", "/", 2)

End Sub

Function Strip(ByVal Source As String, ByVal Seperator As String, ByVal StripCount As Long) As String

Dim myArray As Variant
Dim mySeperatorCount As Long

    mySeperatorCount = Len(Source) - Len(Replace(Source, Seperator, vbNullString))
    myArray = Split(Source, Seperator, mySeperatorCount - StripCount + 2)
    Strip = Left(Source, Len(Source) - Len(myArray(UBound(myArray))))

End Function
相关问题