【发布时间】:2021-10-18 21:48:41
【问题描述】:
我一直在寻找解决方案,但找不到一个可行的或我可以修改的解决方案。我有一个全名列表,可能包含也可能不包含中间名、中间名首字母和后缀。使用 VBA 脚本,我需要将名称解析为适当的单独列,如下所示。 (注 - 后缀可以包括 Jr、Jr.、Sr、Sr.、II、III、IV 和 V...暂时)
我最接近的是这段代码:(其中“emptyRow”已被确定为第一个没有数据的可用行)
Dim MyText As String
Dim i As Integer
Dim MyResult() As String
MyText = Range("A" & emptyRow).Value
MyResult = Split(MyText)
For i = 0 To UBound(MyResult)
Cells(emptyRow, i).Value = MyResult(i)
Next I
但是,它不会对缺少的项目做任何事情,例如中间名或后缀。
关于如何使其发挥作用或其他方法的任何想法?
| (A1)Full Name | (B1)First Name | (C1)Middle Name | (D1)Last Name | (E1)Suffix |
|---|---|---|---|---|
| John Adam Doe Jr. | John | Adam | Doe | Jr. |
| John A Doe Jr | John | A | Doe | Jr |
| John Doe Jr | John | Doe | Jr | |
| John Adam Doe | John | Adam | Doe | |
| John A Doe | John | A | Doe | |
| John Doe | John | Doe |
更新:
所以,这就是我想出的。我敢肯定它可能会更漂亮,但我认为它有效。
MyResult = Split(MyText)
i = UBound(MyResult)
Cells(emptyRow, 1).Value = MyResult(0)
If MyResult(i) = "Jr." Or MyResult(i) = "Jr" Or MyResult(i) = "Sr." Or MyResult(i) = "Sr" Or MyResult(i) = "II" Or MyResult(i) = "ii" Or MyResult(i) = "III" Or MyResult(i) = "IIi" Or MyResult(i) = "Iii" Or MyResult(i) = "IiI" Or MyResult(i) = "iii" Or MyResult(i) = "iIi" Or MyResult(i) = "iiI" Or MyResult(i) = "iII" Or MyResult(i) = "iI" Or MyResult(i) = "Ii" Or MyResult(i) = "IV" Or MyResult(i) = "V" Or MyResult(i) = "iv" Or MyResult(i) = "v" Or MyResult(i) = "Iv" Or MyResult(i) = "iV" Then
If i = 5 Then
Cells(emptyRow, 4).Value = MyResult(i)
Cells(emptyRow, 3).Value = MyResult(3) & " " & MyResult(4)
Cells(emptyRow, 2).Value = MyResult(1) & " " & MyResult(2)
ElseIf i = 4 Then
Cells(emptyRow, 4).Value = MyResult(i)
Cells(emptyRow, 3).Value = MyResult(2) & " " & MyResult(3)
Cells(emptyRow, 2).Value = MyResult(1)
ElseIf i = 3 Then
Cells(emptyRow, 4).Value = MyResult(i)
Cells(emptyRow, 3).Value = MyResult(2)
Cells(emptyRow, 2).Value = MyResult(1)
Else
Cells(emptyRow, 4).Value = MyResult(i)
Cells(emptyRow, 3).Value = MyResult(1)
End If
ElseIf i = 4 Then
Cells(emptyRow, 3).Value = MyResult(3) & " " & MyResult(4)
Cells(emptyRow, 2).Value = MyResult(1) & " " & MyResult(2)
ElseIf i = 3 Then
Cells(emptyRow, 3).Value = MyResult(2) & " " & MyResult(3)
Cells(emptyRow, 2).Value = MyResult(1)
ElseIf i = 2 Then
Cells(emptyRow, 3).Value = MyResult(2)
Cells(emptyRow, 2).Value = MyResult(1)
Else
Cells(emptyRow, 3).Value = MyResult(1)
End If
想法??
【问题讨论】:
-
代码应该如何区分中间名和姓氏?
-
这需要您在手动执行此操作时使用的相同类型的逻辑。文本只有两部分 = 名字 + 姓氏。多于两部分,最后一部分在您的后缀列表中=最后一部分是后缀,然后相应地划分其他部分。等等等等。没有 100% 的单行代码 - 你需要想出一些规则,然后在你的代码中实现这些规则。
-
要建立在蒂姆所说的基础上,最难的部分将是多字姓氏。例如,为什么
Doe Smith是姓氏而不是Adam Doe?你对此有什么规定吗? -
同意如何区分中间名和组合姓氏?其余的很容易做到,但除非你有一些规则/潜力列表等,否则这部分基本上是不可能的。
-
@Simon, chris, Tim, chrisneilsen - 这些都是我在这种情况下遇到的所有问题/问题。这个怎么样: 1)删除后缀,如果存在 2)计算剩余“单词”的数量 3)如果“单词”> 2,则假设第二个是中间名,否则只有 FName,LName 4)位置在各自的单元格中命名组件~~~在VBA中看起来像这样的东西怎么样? (我也会编辑原帖)
标签: excel vba parsing office365