VBA split string by spaces

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

I want a function in excel that i can call and pass a cell into. Input:

Firstname          Lastname      email@mail.com        Firstname      midname     Lastname      email@mail.com 

The number of spaces in between are random. Output should just be an array. The array can have any length since i don't know what the strings look like. Output should be:

Firstname, Lastname, email@mail.com        Firstname, midname, Lastname, email@mail.com 

I will call the function from one cell like =MySplitFunction(A1), and that should put Firstname in A1, Lastname in B1, and email@mail.com in C1. I created a new module and tried the following code:

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

Which gives me output

Firstname 

How do i get it to return the whole array? Is it even possible to write a function in one cell that will put stuff in cells close to it?

EDIT:

回答1:

  • Enter you input data in A1
  • Select the B1:D1 range
  • enter your formula =MySplitFunction(A1)
  • make it an array formula by pressing CTRL + SHIFT + ENTER instead of just ENTER.

To remove the multiple spaces, you could amend your code like this (not super efficient but works):

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 


回答2:

Alternative solution is to:

  1. use RegEx as a first step to remove all spaces
  2. split result of step first based on single spaces left
  3. moreover, because you need to return different element of the text in different cells than additional function parameter will solved that.

This is proposed function:

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 

and this is screen shot presenting how it works:

Important! when calling function in Excel use comma to separate parameters (instead of presented semi-colon due to local-national version of excel I use).



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!