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

Vba 如何将列中的数据拆分为两个单独的列?,vba,excel,Vba,Excel,在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 IsEmp

在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

到目前为止,我找到的解决方案要求手动选择单元格,这对于我处理的数据量来说是不合理的。我找到了此解决方案,但出现以下错误:无效的过程调用或参数

非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
为什么不在列中使用数据~~>文本

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
我知道这个问题已经很老了,但我想为将来可能遇到同样问题的人提供一个答案

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

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


我是VBA新手,因此如果代码的格式或编写不当,我深表歉意。

我正在格式化从Sharepoint导出的数据,如果我必须手动格式化每一列,这将花费大量时间,因为我还必须以其他方式格式化工作表。到目前为止,我一直在使用文本到列,但您发布的VBA方法正是我想要的。谢谢