VBA,使用InstrRev的最后一个"/"

exc*_*guy 0 excel vba excel-vba

我有代码解析字符串上的最后一个单词.即.Stack/Over/Flow会给我"Flow".

但我希望得到"Over/Flow".

这就是我得到的,但只能得到"流动"

arr(counter - 2) = "'" & mid(Text, InStrRev(Text, "/") + 1) & "'"

Sco*_*ner 6

我会用 Split()

Sub lastTwo()
Dim str As String
str = "Stack/Over/Flow"

Dim splt() As String
splt = Split(str, "/")

If UBound(splt) > 0 Then
    Debug.Print splt(UBound(splt) - 1) & "/" & splt(UBound(splt))
End If
End Sub
Run Code Online (Sandbox Code Playgroud)

这是一个功能:

Function lastParts(str As String, delim As String, x As Long) As String
Dim splt() As String
splt = Split(str, "/")

If UBound(splt) + 1 >= x Then
   Dim t As String
   t = "=INDEX(INDEX({""" & Join(splt, """;""") & """},N(IF({1},ROW(" & UBound(splt) - x + 2 & ":" & UBound(splt) + 1 & "))),),)"
   lastParts = Join(Application.Transpose(Application.Evaluate(t)), delim)
Else
    lastParts = str
End If
End Function
Run Code Online (Sandbox Code Playgroud)

它有三个部分,字符串,分隔符和返回数.

可以使用您的代码调用它:

arr(counter-2) = lastParts(Text,"/",2)
Run Code Online (Sandbox Code Playgroud)

或者从工作表中

=lastParts(A1,"/",2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述