在Excel订单上,从第84行开始,列A被指定为姓氏列,列B被指定为名列。无论如何,有时这些订单会在“姓氏”列中以名字和姓氏一起发送。该代码在大多数情况下都有效。如果在A列中有两个用空格隔开的名称,它将暂时将它们移到其他列,然后最后移到A和B列。
Sub FirstSpaceLastNameFix()
Dim LastRow As Integer
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A84:A" & LastRow).Select
Dim rng As Range, Cell As Range
Set rng = Selection
Application.DisplayAlerts = False
Selection.TextToColumns Destination:=Range("A84"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=True, other:=False, FieldInfo:= _
Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Application.DisplayAlerts = True
Range("A84:A" & LastRow).Cut Destination:=Range("EE1")
Range("B84:B" & LastRow).Cut Destination:=Range("A84")
Range("EE1:EE" & LastRow).Cut Destination:=Range("B84")
End Sub
此代码的问题在于,当给出中间名或中间名首字母时,它不能解决问题。当A列中的名字和姓氏不止一个时,有什么方法可以使其识别?如果是这样,是否删除中间名?
在给出中间名的情况下使用此代码,它将把中间名放在A列中,将名字放在B列中,并将姓氏放在C列中。
答案 0 :(得分:0)
这遍历每一行,而不是在每一列中使用文本。
我认为无论采用哪种方法,您都会遇到诸如John Doe III,John Michael Doe(其中John Michael是“名字”)之类的名称的问题,或者有时带有连字符的姓氏不包含连字符,因此John Smith Doe Smith Doe是“姓氏”。
否则...
'"FileWithNames.xls" would have to be matched to your file of course.
Dim wbNames As Workbook: Set wbNames = Application.Workbooks("FileWithNames.xls")
Dim strName As String, strFirst As String, strLast As String, i0 As Long
'Worksheets(1) would also have to be set to match the appropriate sheet.
With wbNames.Worksheets(1)
For i0 = 84 To .UsedRange.Rows.Count
strName = .Cells(i0, 1).Value
If InStr(strName, " ") > 0 Then
strFirst = Left$(strName, InStr(strName, " ") - 1)
strLast = Right$(strName, Len(strName) - InStrRev(strName, " "))
.Cells(i0, 1).Value = strLast
.Cells(i0, 2).Value = strFirst
End If
Next i0
End With