VBA,TRIM部分path

可以说我有一个path:堆栈/溢出/问题/帮助/请。 最终的结果是:help / please。

有没有人有一个代码,我可以说明有多less“/”我想parsing。

它类似于文本列,但我想保持在一个单元格。

谢谢

你可以写一个这样的函数:

 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(":stack/overflow/question/help/please","/",2)评估为"help/please"

你可以使用这个代码(多一点,但应该没问题):

 Public Function custDelim(ByVal str As String, ByVal delim As String, ByVal num As Long) As String Dim holder As Variant holder = Split(str, delim) If num = 0 Then custDelim = "" ElseIf num > 0 Then If num <= UBound(holder) Then holder = Split(str, delim, UBound(holder) - num + 2) custDelim = holder(UBound(holder)) Else custDelim = str End If ElseIf num < 0 Then If Abs(num) <= UBound(holder) Then ReDim Preserve holder(Abs(num) - 1) custDelim = Join(holder, delim) Else custDelim = str End If End If End Function 

=custDelim("very-long-string-in-here","-",2)会输出“in-here”,而使用-2输出“very-long”。

如果你仍然有问题,只要问:)

选项1: excel-vba

处理string的多个部分时,我更喜欢将Split函数用于variables数组中。

 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 

您可能需要将可选参数的缺陷更改为最常用的任何参数。

语法:= trim_part_of_a_path (<原始string> ,[要保留的可选数字],[可选分隔符] 示例:= trim_part_of_a_path(A2)
= trim_part_of_a_path(A2,C2,B2)
= trim_part_of_a_path(A2,1,“/”)

选项2: excel公式

SUBSTITUTE函数有一个可选的[instance_num]参数,它允许您将重复字符的出现次数更改为唯一可以在后续函数计算中find的值。

一对LEN函数与另一个SUBSTITUTE返回一个字符的总发生次数。

MID函数可以使用FIND函数来标识原始文本的一部分,以从上述函数生成的修改后的string中返回。

如果参数超出范围, IFERROR函数可以返回原始string。

 '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) 

当参数可以放入公式引用的单元格中时,基于公式的解决scheme可能效果最佳。


trim_part_of_a_path