如何将一列中的数据分为两个单独的列? [英] How to split data in a column into two separate columns?
问题描述
在Excel中,我有一列名称,格式为"FirstName LastName".我想将整个列分为两列,一列包含所有姓氏,另一列包含所有姓氏.
In Excel, I have a column of names in the format "FirstName LastName". I'd like to split that entire column into two columns, with one containing all of the first names and the other containing all of the last names.
到目前为止,我的代码:
My code so far:
'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
到目前为止,我发现的解决方案要求手动选择单元格,这对于我正在使用的数据量来说是不合理的.我找到了此解决方案,但出现以下错误:无效的过程调用或参数.
The solutions I have found so far have required that the cells be selected manually, which was unreasonable for the amount of data I am working with. I found this solution, but I get the following error: Invalid Procedure call or argument.
推荐答案
非VBA方法
为什么不使用Data ~~> Text to Columns?
Why not use 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
这篇关于如何将一列中的数据分为两个单独的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!