Excel VBA,修剪路径的一部分

Excel VBA,修剪路径的一部分,excel,vba,excel-vba,excel-formula,Excel,Vba,Excel Vba,Excel Formula,假设我有一个路径:stack/overflow/question/help/please。 最终的结果是:帮助/请 是否有人有一个代码,我可以在其中说明我要解析多少“/” 它类似于文本到列,但我希望将其保留在一个单元格中 谢谢您可以编写如下函数: Function RightPart(s As String, d As String, n As Long) As String Dim A As Variant Dim i As Long, ub As Long Dim t

假设我有一个路径:stack/overflow/question/help/please。 最终的结果是:帮助/请

是否有人有一个代码,我可以在其中说明我要解析多少“/”

它类似于文本到列,但我希望将其保留在一个单元格中


谢谢

您可以编写如下函数:

Function RightPart(s As String, d As String, n As Long) As String
    Dim A As Variant
    Dim i As Long, ub As Long
    Dim t As String

    A = Split(s, d)
    ub = UBound(A)
    If n >= ub Then
        RightPart = s
        Exit Function
    End If
    For i = ub - n + 1 To ub
        t = t & A(i) & IIf(i < ub, d, "")
    Next i
   RightPart = t
End Function
函数RightPart(s为字符串,d为字符串,n为长)为字符串
变暗作为变体
暗我一样长,乌布一样长
调暗t作为字符串
A=拆分(s,d)
ub=UBound(A)
如果n>=ub,则
右部分=s
退出功能
如果结束
对于i=ub-n+1到ub
t=t&A(i)和IIf(i
然后
RightPart(“:stack/overflow/question/help/please”,“/”,2)
计算结果为
“help/please”
您可以使用此代码(做得更多,但应该可以):

公共函数custDelim(ByVal str作为字符串,ByVal delim作为字符串,ByVal num作为长字符串)作为字符串
变光支架
支架=拆分(str、delim)
如果num=0,则
custDelim=“”
ElseIf num>0则
如果num

在处理字符串的多个部分时,我更喜欢将

Function trim_part_of_a_path(str As String, _
                             Optional keep As Integer = 1, _
                             Optional delim As String = "/")
    Dim a As Long, tmp As Variant

    tmp = Split(str, delim)
    If UBound(tmp) < keep Then
        trim_part_of_a_path = str
    Else
        trim_part_of_a_path = tmp(UBound(tmp) - keep)
        For a = UBound(tmp) - keep + 1 To UBound(tmp)
            trim_part_of_a_path = _
                trim_part_of_a_path & delim & tmp(a)
        Next a
    End If
End Function
如果可以将参数放入公式引用的单元格中,则基于公式的解决方案可能效果最佳



您可以使用固定宽度定界选项。不清楚您的要求。是否需要一个自定义项,其中提供一个字符串
s
,一个分隔符
d
,还有一个整数
i
,它返回分隔符出现的
ith
右边字符串的一部分?从两端提取的功能非常棒。这是一个类似于'Mid'的旧函数的剩余部分,具有delimeter的开始和长度(在复杂的公式中,使用负数从后面计数比使用额外的bool更容易):P
Function trim_part_of_a_path(str As String, _
                             Optional keep As Integer = 1, _
                             Optional delim As String = "/")
    Dim a As Long, tmp As Variant

    tmp = Split(str, delim)
    If UBound(tmp) < keep Then
        trim_part_of_a_path = str
    Else
        trim_part_of_a_path = tmp(UBound(tmp) - keep)
        For a = UBound(tmp) - keep + 1 To UBound(tmp)
            trim_part_of_a_path = _
                trim_part_of_a_path & delim & tmp(a)
        Next a
    End If
End Function
'return a portion of string while retaining x number of delimiters
=IFERROR(MID(A2, FIND(CHAR(167), SUBSTITUTE(A2, B2, CHAR(167), LEN(A2)-LEN(SUBSTITUTE(A2,B2,""))-C2))+1, LEN(A2)), A2)