VBS to split one column in two columns

匆匆过客 提交于 2020-12-06 11:50:00

问题


Let's say for example, i have one column filled with names, each name in one cell.

    First_Name_1 Last_Name_1
    First_Name_2 Last_Name_2
    First_Name_3 Last_Name_4

First name and last name are separated by space. How can i split this column in two columns, using Visual Basic Script so that i will have First_Name in one column and Last_name in a column next to it?

Already tried this code, but can't manage to make it work.

    objExcel.ActiveSheet.Columns(4).Select
    Do Until IsEmpty(ActiveCell)
    'Search for position of space within the cell
    SplitPoint = InStrRev(ActiveCell, " ", -1, vbTextCompare)
    'Put the last name in the column next to the source column
    ActiveCell.Offset(0, 1) = Trim(Left(ActiveCell, SplitPoint))
    'Replace the source column with the first name
    ActiveCell.Offset(0, 0) = Trim(Mid(ActiveCell, SplitPoint))
    Loop

Thanks in advance!


回答1:


Excel has a TextToColumns() function that can do what you're looking for with a single function call.

objExcel.ActiveSheet.Columns(4).TextToColumns , , , , , , , True

Might make more sense with the params shown. Your data is space-delimited so we just need to set the 8th param to True. The rest can be omitted to accept the defaults.

objExcel.ActiveSheet.Columns(4).TextToColumns _
    , _        ' Destination (optional, defaults to source)
    , _        ' DataType (optional, defaults to xlDelimited)
    , _        ' TextQualifier (optional, defaults to xlTextQualifierDoubleQuote)
    , _        ' ConsecutiveDelimiter
    , _        ' Tab-delimited? (optional, defaults to False)
    , _        ' Semicolon-delimited? (optional, defaults to False)
    , _        ' Comma-delimited? (optional, defaults to False)
    True       ' Space-delimited?



回答2:


you are not moving to the next cell of the range...

Add:

ActiveCell.Offset(1, 0).Activate

I'd add something to check for double spaces (remove one), no spaces and double names or initials (Mary Lou Smith, John M. Lewis).

Ciao



来源:https://stackoverflow.com/questions/22952693/vbs-to-split-one-column-in-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!