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

时间:2013-04-03 16:16:58

标签: 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 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

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

2 个答案:

答案 0 :(得分:5)

非VBA方法

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

enter image description here

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

答案 1 :(得分:1)

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

我知道这个问题很老了,但是对于将来可能会遇到同样问题的人分享答案。

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

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

我对VBA很陌生,如果代码格式化或编写不当,我会道歉。

相关问题