2013-04-03 130 views
2

在Excel中,我有名字的列的格式为“姓”。我想将整列分成两列,一列包含所有的名字,另一列包含所有的姓氏。如何将列中的数据拆分为两个单独的列?

到目前为止我的代码:

'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 

这是不合理的,我处理的数据量,我发现迄今已要求该细胞可手动选择的解决方案。我发现这个解决办法,但我得到以下错误:无效的过程调用或参数

回答

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 
+0

我格式化从SharePoint,这需要大量的时间,如果我必须手动格式化每个柱因为我到片材以其他方式格式化,以及导出的数据。到目前为止,我一直在使用文本到列,但是你发布的VBA方法是我正在寻找的。谢谢。 – Hunterhod

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 

我知道这个问题是很老,但共享一个答案的人谁可能会遇到同样的问题在未来。

我也碰到这个问题,迷迷糊糊的我正在寻找关于如何分割一列的答案。我尝试了循环方法,但处理需要很长时间。 我已经尝试了将文本转换为列到VBA的直接转换。处理时间几乎是即时的,因为它与单击TextToColumns相同。

以我溶液上方,我设置与数据的列A(即,名字&名字)用于分离为一个范围。在目标中,我放置了希望分割数据出现的范围(即列B为名,列C为姓)。分隔符是一个空格。 它对我来说工作得很好。到目前为止,我已经在2000行数据中测试了代码。

我很新的VBA所以道歉,如果代码可能被格式化或写得不好。

相关问题