Link to home
Start Free TrialLog in
Avatar of Bryan Scott
Bryan ScottFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Text to Columns in VBA

Hi everyone, i have a number of columns in a worksheet separated by a comma. The number of columns may change and is not fixed. I have tried using the macro recorder and looked online but cannot seem to work this out. i need each of the columns split but do not want to lose any data? I hav attached a sample of the work book for you. SAMPLE.xlsx
Avatar of nutsch
nutsch
Flag of United States of America image

Can you have more than one comma per cell?
Do the columns need to match, i.e. if cell A2 has three commas, and A3 has two, does B3 start at column C or column D?

Thomas
Avatar of TommySzalapski
If there's always one comma per cell then something like this should work.
Public Sub TextToCols()
colCount = UsedRange.Columns.Count
For i = 1 To colCount
Columns(2 * i).Insert
Columns(2 * i - 1).TextToColumns Comma:=True
Next
End Sub

Open in new window

Of course for that many columns it will be slow so you'll want to turn off screen updating.
Every time you do that, you need to handle crashes and turn it back on even if there's an error. So use this and use the original code (comment out the new lines) if you need to debug.
Public Sub TextToCols()
On Error GoTo crash
Application.ScreenUpdating = False
colCount = UsedRange.Columns.Count
For i = 1 To colCount
Columns(2 * i).Insert
Columns(2 * i - 1).TextToColumns Comma:=True
Next
crash:
Application.ScreenUpdating = True
End Sub

Open in new window

Avatar of Bryan Scott

ASKER

it will only ever be 1 comma that splits the data

Tommy, your solution failed at "colCount = UsedRange.Columns.Count"
That is just because of where the code is. I was assuming the code was in a particular sheet.
Add
Worksheets("Sheet1").
(or whatever the sheet's name is)
in front of UsedRange and Columns like this:
Public Sub TextToCols()
On Error GoTo crash
Application.ScreenUpdating = False
colCount = Worksheets("Sheet1").UsedRange.Columns.Count
For i = 1 To colCount
Worksheets("Sheet1").Columns(2 * i).Insert
Worksheets("Sheet1").Columns(2 * i - 1).TextToColumns Comma:=True
Next
crash:
Application.ScreenUpdating = True
End Sub

Open in new window

Thanks Tommy this works great, do you know how to change this to start from column AR onwards?
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
brilliant thanks so much!