VBA,TRIM是Path的一部分

时间:2016-03-04 20:59:38

标签: excel vba

假设我有一条路径:stack / overflow / question / help / please。 最终结果是:help / please。

有没有人有一个代码,我可以说明我要解析多少“/”。

它类似于文本到列,但我想将它保存在一个单元格中。

由于

3 个答案:

答案 0 :(得分:3)

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

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"

答案 1 :(得分:2)

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

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)将输出&#34; in-here&#34;使用-2时会打印非常长的&#34;。

如果您仍有疑问,请询问:)

答案 2 :(得分:1)

Option 1:

在处理字符串的多个部分时,我更喜欢将Split function用于变量数组。

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

您可能希望将可选参数的defults更改为最常用的任何参数。

  

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

Option 2:

SUBSTITUTE function有一个可选的 [instance_num] 参数,允许您将重复字符的一个匹配项更改为可在后续函数计算中找到的唯一字符。

一对LEN function与另一个SUBSTITUTE返回一个字符的总出现次数。

MID function可以使用FIND function来标识要从上述函数生成的修改后的字符串返回的原始文本部分。

如果参数超出范围,

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

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

trim_part_of_a_path