String splitter as long as there is something in the cell

I have this code for splitting strings. Currently, if the counter is equal to the number of rows on which data is present, it will work correctly. However, this number of rows is a variable. How to make the loop cycle work as long as there is data?

Sub SplitToColumns()

    Range("A1").Select
    For Counter = 0 To 100 Step 1

        Selection.TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
            Tab:=False, Semicolon:=False, Comma:=True, Space:=False, _
            Other:=False, _
            FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
            TrailingMinusNumbers:=True
        ActiveCell.Offset(1, 0).Select
    Next Counter
End Sub
+4
source share
1 answer

Something like that:

get the row number of the last completed row in column A. (Replace the column of your choice). Then use this line number in a for loop, but start at 1, not from scratch. Remove debug.print if no longer required.

Sub SplitToColumns()
Dim rowCount As Long
rowCount = Cells(rows.Count, "A").End(xlUp).Row
Debug.Print rowCount

    Range("A1").Select
    For Counter = 1 To rowCount Step 1

        Selection.TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
            Tab:=False, Semicolon:=False, Comma:=True, Space:=False, _
            Other:=False, _
            FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
            TrailingMinusNumbers:=True
        ActiveCell.Offset(1, 0).Select
    Next Counter
End Sub

. , , TextToColumns. , TextToColumns , .

, , , A1, A, .

TextToColumns , . , , !

Sub SplitToColumns()
    Dim rowCount As Long
    Dim ws As Worksheet

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row

        .Range("A1:A" & rowCount).TextToColumns _
            Destination:=.Range("A1"), _
            DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, _
            ConsecutiveDelimiter:=False, _
            Tab:=False, _
            Semicolon:=False, _
            Comma:=True, _
            Space:=False, _
            Other:=False, _
            FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
            TrailingMinusNumbers:=True
    End With
End Sub
+5

All Articles