如何拆分文本并循环到下一行

时间:2019-02-06 17:41:26

标签: excel vba loops split

我正在使用split函数使用空格分割文本。我已经有了宏来分割文本,但是我很难让循环移动到下面的下一行来分割文本。

Sub Split_Text_Test1()

Dim Txt As String
Dim i As Integer
Dim FullName As Variant

Range("A1").Select

Txt = ActiveCell.Value

FullName = Split(Txt, " ")

For i = 0 To UBound(FullName)
    Cells(1, i + 1).Value = FullName(i)
Next i

End Sub

4 个答案:

答案 0 :(得分:1)

在从A1开始时,您可能需要更改循环内部的位。假设您要输入A2及以下的条目。通常不建议使用“选择/激活”功能,但不是很可靠。

经过修改可跨列而不是向下移动。

For i = 0 To UBound(FullName)
    Range("A1").Offset(,i + 1).Value = FullName(i)
Next i

也就是说,您可以完全避免循环并使用

Range("B1").Resize(, UBound(FullName) + 1).Value = FullName

答案 1 :(得分:0)

Sub Split_Text_Test1()

Dim Txt As String
Dim i As Integer
Dim FullName As Variant
Dim R As Integer, C As Integer
Range("A1").Select ' assumes that the cells below that are empty 

Txt = ActiveCell.Value

FullName = Split(Txt, " ")
R = ActiveCell.Row
C = ActiveCell.Column
For i = 0 To UBound(FullName)
    Cells(R + 1 + i, C).Value = FullName(i)
Next i

End Sub

答案 2 :(得分:0)

在这种情况下,我将使用一个循环(您的解决方案与此相差不远):

Dim Txt As String
Dim i As Integer
Dim FullName As Variant
Dim R As Integer, C As Integer, MaxR as Integer
C = 1 ' can be another loop as well
For R = 1 to 1000

Txt = Trim(Cells(r,1).Value) ' will remove space from start and end
FullName = Split(Txt, " ")

For i = 0 To UBound(FullName)
    Cells(R , C + 1 + i ).Value = FullName(i)
Next i

Next R

答案 3 :(得分:0)

我在您的代码中添加了一些内容,看是否符合您的目的。但是,正如SJR所说的,“数据”菜单中的“文本到列”选项将花费更少的精力。

Sub Split_Text_Test1()

Dim Txt As String
Dim i As Integer
Dim FullName As Variant
Dim lastRow As Long
Dim myRange As Range

With ActiveSheet.UsedRange
        lastRow = .Rows(.Rows.Count).Row
End With
Debug.Print lastRow

'Range("A1").Select

Set myRange = ActiveSheet.Range("A1", "A" & lastRow)

    For Each cell In myRange

        Txt = cell.Value

        FullName = Split(Txt, " ")

            For i = 0 To UBound(FullName)
                Cells(cell.Row, i + 1).Value = FullName(i)
            Next i
    Next cell

End Sub