我想以First Last格式取名,并将其更改为Last,First。我知道我可以通过一个公式来解决这个问题,但我想要变得复杂。
如果您在我的代码中看到任何危险信号或改进建议,请告知我们。
Function LastFirst(Name_FL As String)
'This only works if there is a single space in the cell - Will Error If Spaces <> 1
Length = Len(Name_FL) 'Establishes Length of String
Spaces = Length - Len(Application.WorksheetFunction.Substitute(Name_FL, " ", "")) 'Number of spaces
If Spaces <> 1 Then
LastFirst = "#SPACES!#" 'Error Message
Else
SpaceLocation = Application.WorksheetFunction.Find(" ", Name_FL, 1) 'Location of space
Last = Right(Name_FL, Length - SpaceLocation) 'Establishes Last Name String
First = Left(Name_FL, SpaceLocation) 'Establishes First Name String
LastFirst = Application.WorksheetFunction.Proper(Last & ", " & First) 'Puts it together
End If
End Function 'Ta-da
答案 0 :(得分:1)
您可以将其简化为:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) > 1 Then
LastFirst = "#SPACES#"
Else
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
End If
End Function
这里的逻辑是:
#SPACES#
" "
作为分隔符拆分字符串。", "
并使用split数组的第一个索引。StrConv()
将所有内容转换为正确的大小写。
您可能还想为否空格添加另一项检查:
If InStr(Name_FL, " ") > 0 Then
'// There is a space in the string
Else
'// There is no space in the string
End If
也可以通过稍微改变上面例子的逻辑来测试:
Function LastFirst(Name_FL As String) As String
If (Len(Name_FL) - Len(Replace(Name_FL, " ", ""))) = 1 Then
LastFirst = StrConv(Split(Name_FL, " ")(1) & ", " & Split(Name_FL, " ")(0), vbProperCase)
Else
LastFirst = "#SPACES#"
End If
End Function
进一步阐述功能:
您可以在此处看到我使用了一些VBA功能来代替您的WorksheetFunction
方法。
Len()
返回 Len 字符串的第g。Replace()
执行它在锡上所说的内容 - 用另一个替换给定的字符串。StrConv()
Conv 对相应的案例(例如vbProperCase
)设置了 Str 。Split()
从字符串创建一个从零开始的单维数组,通过拆分将其放在给定的分隔符上。最后 - 不要忘记在函数头中指定返回值:
Function LastFirst(Name_FL As String)
的 As String
强> <~~ return type