Search code examples
vbaexceltext-to-column

Text to column for loop


So basically I have multiple columns of text that I want to change to numbers. Now the issue i face is ive got the code but i dont understand how to run a loop on it to choose the next third column. This is my code:

Sub Texscolumn()

Range("AI2:AI96").Select
Selection.TextToColumns Destination:=Range("AI2"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
    :=Array(Array(1, 1), Array(2, 9), Array(3, 9), Array(4, 9), Array(5, 9), Array(6, 9), Array(7, 9), Array(8, 9)), TrailingMinusNumbers:= _
    True
 End Sub

So the next column I want is suppose AJ2:AJ96. I cant seem to figure out how to make a for loop with changing columns like this.


Solution

  • At least 2 options :

    Sub Texscolumn()
    Dim j As Integer
    With Sheets("sheet1")
        For j = 35 To 36
            .Range(.Cells(2, j), .Cells(96, j)).TextToColumns Destination:=.Cells(2, j), _
                                DataType:=xlDelimited, _
                                TextQualifier:=xlDoubleQuote, _
                                ConsecutiveDelimiter:=True, _
                                Tab:=True, _
                                Semicolon:=False, _
                                Comma:=False, _
                                Space:=True, _
                                Other:=False, _
                                FieldInfo:=Array(Array(1, 1), Array(2, 9), Array(3, 9), Array(4, 9), Array(5, 9), Array(6, 9), Array(7, 9), Array(8, 9)), _
                                TrailingMinusNumbers:=True
        Next i
    End With
    End Sub
    

    or

    Sub Texscolumn()
    Dim Rg As Range
    Dim i As Integer
    Set Rg = Sheets("sheet1").Range("AI2:AI96")
    With Rg
        For i = 1 To 2
            .TextToColumns Destination:=.Cells(1, 1), _
                                DataType:=xlDelimited, _
                                TextQualifier:=xlDoubleQuote, _
                                ConsecutiveDelimiter:=True, _
                                Tab:=True, _
                                Semicolon:=False, _
                                Comma:=False, _
                                Space:=True, _
                                Other:=False, _
                                FieldInfo:=Array(Array(1, 1), Array(2, 9), Array(3, 9), Array(4, 9), Array(5, 9), Array(6, 9), Array(7, 9), Array(8, 9)), _
                                TrailingMinusNumbers:=True
            Set Rg = .Offset(0, 1)
        Next i
    End With
    End Sub