VBA中的字符串操作

时间:2014-07-18 03:26:20

标签: string excel vba excel-vba texttrimming

我有单列需要拆分为多个,例如excel中的Text-to-columns。然而,这是一个小小的挑战。传统的分隔符不起作用。考虑下面的字符串

Original: Domain\Domain Admins Domain2\User Group Domain3\Developers .....(And so on)
Required: Domain\Domain Admins | Domain2\User Group | Domain3\Developers .....(And so on)

所需字符串中的管道意味着它需要在此处拆分并根据字符串的长度复制到下一列。

我在A列中有506行的列表。 我使用下面的公式来检查" \"在列B中,计数范围为0-66

=LEN(A2)-LEN(SUBSTITUTE(A2,"\",""))

我需要帮助来编写逻辑

  1. 查找" \"在字符串
  2. 在" \"之前找到空间分裂
  3. 我使用了以下代码,但它没有达到目的

    Range("A1:A506").Select
    Selection.TextToColumns 
    

    请帮助我们牢记第1点和第2点的代码。

1 个答案:

答案 0 :(得分:0)

这是一个你可以使用的函数,注释+代码是不言自明的

<强>代码:

Function SplitThis(InputStr As String) As Variant

    Dim SplitStr() As String, SubStr() As String, RightmostStr As String
    Dim OutputStr() As String

    Dim Delim_Level1 As String, Delim_Level2 As String, Delim_Cut As String

    Delim_Level1 = "\"
    Delim_Level2 = " "
    Delim_Cut = "}"         ' Any character you are guaranteed not to find in your original string

    'InputStr = "Domain\Domain Admins Domain2\User Group Domain3\Developer"
    SplitStr = Split(InputStr, Delim_Level1)

    ' SplitStr(0) = "Domain"
    ' SplitStr(1) = "Domain Admins Domain2"
    ' SplitStr(2) = "User Group Domain3"
    ' SplitStr(3) = "Developer"

    Dim i As Long
    For i = 1 To UBound(SplitStr) - 1                   ' i.e. 1 --> 2
        SubStr = Split(SplitStr(i), Delim_Level2)
        RightmostStr = SubStr(UBound(SubStr))

        ReDim Preserve SubStr(0 To UBound(SubStr) - 1)

        SplitStr(i) = Join(SubStr, Delim_Level2) & Delim_Cut & RightmostStr

    Next i

    ' SplitStr(0) = "Domain"
    ' SplitStr(1) = "Domain Admins{Domain2"
    ' SplitStr(2) = "User Group{Domain3"
    ' SplitStr(3) = "Developer"

    ' These are joined to create:
    ' "Domain\Domain Admins}Domain2\User Group}Domain3\Developer"
    '
    ' Which is split at the character "}" to create the output

    OutputStr = Split(Join(SplitStr, Delim_Level1), Delim_Cut)

    Dim OutputVariant() As Variant
    ReDim OutputVariant(0 To 0, 0 To UBound(OutputStr))

    For i = 0 To UBound(OutputStr)
        OutputVariant(0, i) = OutputStr(i)
    Next i

    SplitThis = OutputVariant
End Function

<强>用法:

Cell A1   : "Domain\Domain Admins Domain2\User Group Domain3\Developer"
Cell A3:C3: {=SplitThis(A1)}       ' Array formula

<强>截图:

enter image description here

唠叨怀疑:我有这种感觉,最有效的方法是使用一些基于Regex的解决方案,但现在应该这样做。