Excel拆分字符串循环

时间:2014-09-10 09:39:07

标签: excel vba excel-vba

我有4个不同的范围。我需要拆分这些范围的内容。所以细胞包含; Tom Jerry Bugs Bunny Jack Sparrow Bob。我想把它分成7个不同的细胞。我已经在互联网上查看了如何使用以下代码执行这样的拆分。

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

我的问题是我需要在一个循环中这样它会经过一个范围,比如说(“H1:H200”)这就是我被卡住了,我已经开始循环,但是无法让分裂在里面工作它。这是我的循环的开始:

Dim rCell As Range
Dim rRng As Range

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

对此问题的任何帮助将不胜感激!感谢。

3 个答案:

答案 0 :(得分:1)

为什么重新发明轮子?你可以使用TextToColumns。例如:

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

答案 1 :(得分:1)

你可以在For里面使用For。像,

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

答案 2 :(得分:0)

最后我自己得出了这个结论,谢谢你的回答

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 下一步