简体   繁体   中英

Excel split string loop

I have 4 different ranges. I need to split the contents of these ranges. so the cell contains; Tom Jerry Bugs Bunny Jack Sparrow Bob. And I want to split that into 7 different cells. I have looked on the internet and have discover how to perform a split like this with the following code.

Dim text As String
Dim a As Integer
Dim name As Variant
text = ActiveCell.Value
name = Split(text, " ")
For a = 0 To UBound(name)
Cells(1, a + 1).Value = name(a)
Next a

My issue is i need this inside a loop so it will go through a range, say ("H1:H200") and this is were I am stuck, I have started the loop, but cannot get the split to work inside it. Here is the start of my loop:

Dim rCell As Range
Dim rRng As Range

Set rRng = Range("H1:H200")
For Each rCell In rRng.Cells
 'split string here.

Any help on this issue would be appreciated! Thanks.

Why reinvent the wheel? You could just use TextToColumns . For example:

Dim rCell As Range
Dim rRng As Range

Set rRng = Range("H1:H200")
For Each rCell In rRng.Cells
    rCell.TextToColumns Destination:=rCell.Offset(0, 1), Space:=True
Next

You could use the For inside the For. Something like,

Dim txtStr As String
Dim aCtr As Integer
Dim nameVar() As String
Dim rCell As Range
Dim rRng As Range

Set rRng = Range("H1:H200")
For Each rCell In rRng.Cells
    txtStr = rCell.Value
    nameVar = Split(txtStr, " ")
    For aCtr = 0 To UBound(nameVar)
        Cells(1, aCtr + 1).Value = nameVar(aCtr)
    Next
Next

Came to this conclusion in the end on my own, thanks for the answers though

Dim bb As Integer
Dim text As String
Dim aa As Integer
Dim name As Variant
Dim cc As Range
Dim rng As Range
bb = 2
Set rng = Range("H2:H200")
For Each cc In rng
 text = cc.Value
 name = Split(text, " ")
 For aa = 0 To UBound(name)
 'Ubound finds the end of an array
 Cells(bb, aa + 1).Value = name(aa)
Next aa

bb = bb + 1 Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM