我正在尝试使用MID
修剪字符串,以便删除/
的倒数第二个之后的所有内容。
mom/dad/brother/sister/me/ to mom/dad/brother/sister/
thor/ironman/thanos/ to thor/ironman/
我正在尝试使用Mid
,Left
和InStrRev
的组合,但可能会对此有所考虑。我的东西在下面,什么也没发生。...
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
答案 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
之前:
之后:
答案 1 :(得分:1)
@Craners解决方案也可以使用,并且速度更快
Len(Range - 1)
无效。这应该是Len(Range) - 1
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