如何将列中的数据拆分为两个单独的列?

Hun*_*hod 2 excel vba excel-vba

在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
Run Code Online (Sandbox Code Playgroud)

到目前为止我找到的解决方案要求手动选择单元格,这对我正在使用的数据量是不合理的.我找到了这个解决方案,但是我收到以下错误:无效的过程调用或参数.

Sid*_*out 5

非VBA方法

为什么不使用数据~~>文本到列?

在此输入图像描述

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
Run Code Online (Sandbox Code Playgroud)