【问题标题】:VBS to split one column in two columnsVBS将一列分成两列
【发布时间】:2014-04-09 04:17:07
【问题描述】:

比如说,我有一列填满了名字,每个名字都在一个单元格中。

    First_Name_1 Last_Name_1
    First_Name_2 Last_Name_2
    First_Name_3 Last_Name_4

名字和姓氏用空格分隔。 如何使用 Visual Basic 脚本将此列拆分为两列,以便将 First_Name 放在一列中,将 Last_name 放在旁边的一列中?

已经尝试过此代码,但无法使其工作。

    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

提前致谢!

【问题讨论】:

    标签: vbscript split two-columns


    【解决方案1】:

    Excel 有一个 TextToColumns() 函数,只需一次函数调用即可完成您所寻找的工作。

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

    使用显示的参数可能更有意义。您的数据以空格分隔,因此我们只需将第 8 个参数设置为 True。其余的可以省略以接受默认值。

    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】:

    您没有移动到范围的下一个单元格...

    添加:

    ActiveCell.Offset(1, 0).Activate

    我会添加一些内容来检查双空格(删除一个),没有空格和双名或首字母缩写(Mary Lou Smith、John M. Lewis)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多