Search code examples
excelvba

How to determine the resulting range of TextToColumns


Is there a good way to get the resulting range after using Range.TextToColumns in VBA?

What I'm trying to do is split some data into columns, and then perform an action on each resulting cell. If I knew ahead of time how big the resulting range would be I could just select it, but I want to do it dynamically for any size of data.

Call Selection.TextToColumns(DataType:=xlDelimited, comma:=True)
resultRange = ?????
Call OtherSub(resultRange)

Solution

  • I ended up just manually interrogating the data to figure out the result. It seems like this puts me most of the way to just re-coding text to columns anyway, but it works.

    Set selectedRange = Selection
    
    maxCol = 0
    For Each rng In selectedRange
        sTxt = rng.Value
        iCol = UBound(Split(sTxt, ",")) + 1
        If iCol > maxCol Then
            maxCol = iCol
        End If
    Next rng
    
    Call Selection.TextToColumns(DataType:=xlDelimited, _
        comma:=True, _
        Space:=False, semicolon:=False, Tab:=False, other:=False, _
        ConsecutiveDelimiter:=False)
    
    Set rng = selectedRange.Resize(, maxCol)