【问题标题】:How to split data in a column into two separate columns?如何将列中的数据拆分为两个单独的列?
【发布时间】:2017-06-13 13:47:07
【问题描述】:

在 Excel 中,我有一列名称格式为“FirstName LastName”的名称。我想将整列分成两列,一列包含所有名字,另一列包含所有姓氏。

到目前为止我的代码:

    'Splitting the Traveler Display Name column
    Dim SplitPoint As Long
    'L2 is the column containing names to be split
    Range("L2").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

到目前为止,我发现的解决方案要求手动选择单元格,这对于我正在处理的数据量来说是不合理的。我找到了这个解决方案,但我收到以下错误:Invalid Procedure call or argument

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    非 VBA 方法

    为什么不使用 Data~~>Text To Columns?

    VBA 方法

    Option Explicit
    
    Sub Sample()
        Dim ws As Worksheet
        Dim LastRow As Long, i As Long
        Dim tmpArray() As String
    
        '~~> This is the relevant sheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
    
        With ws
            LastRow = .Range("L" & .Rows.Count).End(xlUp).Row
    
            For i = 2 To LastRow
                If InStr(1, .Range("L" & i).Value, " ") Then
                    tmpArray = Split(.Range("L" & i).Value, " ")
                    .Range("M" & i).Value = tmpArray(0)
                    .Range("N" & i).Value = tmpArray(1)
                End If
            Next i
        End With
    End Sub
    

    【讨论】:

    • 我正在格式化从 Sharepoint 导出的数据,如果我必须手动格式化每一列,这会花费很多时间,因为我还必须以其他方式格式化工作表。到目前为止,我一直在使用文本到列,但是您发布的 VBA 方法正是我想要的。谢谢。
    【解决方案2】:
    Private Sub Sample()
        Dim myRng As Range
        Dim LastRow As Long
    
        LastRow = Sheets("Sample1").UsedRange.Rows.Count
    
        With Sheets("Sample1")
            Set myRng = Sheets("Sample1").Range("A2:A" & LastRow)
        End With
    
        myRng.TextToColumns _
          Destination:=Range("B2:C2"), _
          DataType:=xlDelimited, _
          Tab:=False, _
          Semicolon:=False, _
          Comma:=False, _
          Space:=True, _
          Other:=False
    
    End Sub
    

    我知道这个问题已经很老了,但是为将来可能遇到相同问题的任何人分享一个答案。

    我在寻找有关如何拆分列的答案时偶然发现了这个问题。我尝试了循环方法,但需要很长时间才能处理。 我已经尝试将文本到列的字面翻译为 VBA。处理时间几乎是即时的,因为它与单击 TextToColumns 相同。

    在上面的解决方案中,我将 A 列设置为包含数据(即 FirstName 和 LastName)以便拆分为 Range。在目标中,我将范围放置在希望拆分数据出现的位置(即,B 列代表名字,C 列代表姓氏)。分隔符是一个空格。 它对我来说很好。到目前为止,我已经在 2000 行数据中测试了代码。

    我对 VBA 很陌生,如果代码格式或编写不当,我深表歉意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-11
      • 2021-10-26
      • 2015-04-03
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 2020-11-08
      • 2018-06-25
      相关资源
      最近更新 更多