简体   繁体   中英

Loop Text to Columns macro in Excel for multiple selected columns

I am trying to perform the "Text to Columns" feature on several columns of data in Excel. How can I modify the VBA script of my macro to do this? Right now, I can only select one column for my macro, but I'd like to select multiple columns, and have this loop through somehow.

Also, is there any way to write script that clicks "okay" for me, when it asks if I can overwrite the data in the next column?

Sub text2col()
'
' text2col Macro
'
' Keyboard Shortcut: Option+Cmd+k
'
    Selection.TextToColumns Destination:=Range(ActiveCell.Address), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1))
End Sub
  • change 1 to the column number of the 1st column you need to change
  • change 10 to the column number of the last column you need to change
  • columns are numbered from the left (A) starting with 1

Make sure you pay attention to Mark Wickett 's warning in his comment.

Sub text2col()
'
' text2col Macro
'
' Keyboard Shortcut: Option+Cmd+k
'
Dim Col as Integer

  Application.DisplayAlerts = False
  For Col = 1 to 10 
    Selection.TextToColumns Destination:=Range(ActiveCell.Address), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
    :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1))
  Next
  Application.DisplayAlerts = True
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM