关于excel:VBA按空格分割字符串

VBA split string by spaces

我想要一个可以调用并传递单元格的Excel中的函数。 输入:

1
2
Firstname          Lastname      [email protected]      
Firstname      midname     Lastname      [email protected]

两者之间的间隔数是随机的。 输出应该只是一个数组。 该数组可以有任何长度,因为我不知道字符串是什么样子。 输出应为:

1
2
Firstname, Lastname, [email protected]      
Firstname, midname, Lastname, [email protected]

我将从一个像=MySplitFunction(A1)这样的单元格中调用该函数,该函数应该将Firstname放在A1中,Lastname放在B1中,并将[email protected]放在C1中。 我创建了一个新模块并尝试了以下代码:

1
2
3
Function MySplitFunction(s As String) As String()
    MySplitFunction = Split(s,"")
End Function

这给了我输出

1
Firstname

我如何得到它返回整个数组? 甚至有可能在一个单元格中编写一个函数,该函数会将东西放入靠近它的单元格中?

编辑:

enter image description here


  • 在A1中输入您输入的数据
  • 选择B1:D1范围
  • 输入您的公式=MySplitFunction(A1)
  • 通过按CTRL + SHIFT + ENTER而不是ENTER使其成为数组公式。

要删除多个空格,您可以像这样修改代码(效率不是很高,但是可以):

1
2
3
4
5
6
7
8
9
10
Function MySplitFunction(s As String) As String()
    Dim temp As String

    Do
      temp = s
      s = Replace(s," ","") 'remove multiple white spaces
    Loop Until temp = s

    MySplitFunction = Split(Trim(s),"") 'trim to remove starting/trailing space
End Function


替代解决方案是:

  • 使用RegEx作为删除所有空格的第一步
  • 根据剩余的单个空格分割第一步的结果
  • 此外,因为您需要在不同的单元格中返回文本的不同元素,否则其他函数参数将解决该问题。
  • 建议的功能:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    Public Function MySplitFunction(sMark As String, nTh As Integer) As String

    On Error GoTo EH
        'regexp declaration
        Dim objRegExp As Object
        Set objRegExp = CreateObject("vbscript.regexp")

        Dim tmpTXT As String
        Dim tmpArr As Variant
        With objRegExp
            .Global = True
            .Pattern ="\\s+"

            tmpTXT = .Replace(sMark,"")
        End With

        tmpArr = Split(tmpTXT,"")
        MySplitFunction = tmpArr(nTh - 1)

    Exit Function
    EH:
        MySplitFunction =""

    End Function

    这是显示其工作原理的屏幕截图:

    enter image description here

    重要!在Excel中调用函数时,请使用逗号分隔参数(而不是由于我使用的是excel的本地国家版本,因此不使用分号)。