VBA,使用InstrRev的倒数第二个“ /”

时间:2018-09-21 17:36:56

标签: excel vba excel-vba

我有解析字符串上最后一个单词的代码。 即。 Stack / Over / Flow会给我“流量”。

但是我想获得“ Over / Flow”。

这就是我得到的,但是只能获得“流”

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

2 个答案:

答案 0 :(得分: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

以下是执行此操作的函数:

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

它包含三个部分,字符串,定界符和返回数。

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

arr(counter-2) = lastParts(Text,"/",2)

或从工作表中

=lastParts(A1,"/",2)

enter image description here

答案 1 :(得分:3)

最初误解了问题。您可以嵌套_addParentTeardownLogic个呼叫

InStrRev()