Forum Discussion
How do I make text to columns automated?
Sub ConvertCSVToTable()
Dim ws As Worksheet
Dim lastRow As Long
Dim lastCol As Long
Dim tbl As ListObject
' Set the active sheet as the target
Set ws = ActiveSheet
' Find the last row and column with data
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' Select the data range
ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol)).Select
' Perform Text to Columns with semicolon delimiter
Selection.TextToColumns _
Destination:=ws.Cells(1, 1), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=True, _
Comma:=False, _
Space:=False, _
Other:=False
' Recalculate last column after Text to Columns
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' Format the resulting range as a table
Set tbl = ws.ListObjects.Add(xlSrcRange, ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol)), , xlYes)
tbl.TableStyle = "TableStyleMedium2" ' Adjust the table style as needed
MsgBox "Data delimited and formatted as a table."
End Sub