将名称转换为适当的格式

我经常find需要处理的名字,并调和他们的一些信息。 这些名称通常会以多种不同的格式出现。 我现在的VBA脚本如下所示:

Private Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Or Target.HasFormula Then Exit Sub On Error Resume Next If Not Intersect(Target, Range("B:B")) Is Nothing Then Application.EnableEvents = False Target.Value = StrConv(Target.Value, vbProperCase) Application.EnableEvents = True End If On Error GoTo 0 End Sub 

它把名字改为正确的情况下,但我也希望自动大写的名字在前面,用逗号分隔(如SMITH,约翰)。

在研究中,我发现以下公式工作出色,但这不是在VBA中 – 我需要它来自动转换同一个单元格:

 =RIGHT(A1,LEN(A1)-LEN(LEFT(A1,FIND(",",A1)-1))-2) & " " & LEFT(A1,FIND(",",A1)-1) 

无论如何,如果我能在VBA脚本中使用这个公式,那么是否还会有呢?

最后,如果这个剧本可以识别出特定的姓氏,尤其是把一个符号后面的字母大写(如Mary-Lee / O'Connor),那么我会感到惊讶。

任何build议将不胜感激! 提前致谢!

我把你的工作表公式转换成VBA,你可以使用INSTR得到与FIND相同的结果,参数以相反的顺序传递给它,但除此之外它是相同的。 (我做了一个名为A1的string,以便比较你的例子)

  Dim A1 As String A1 = Target.Value If (InStr(A1, ",") > 0) Then Target.Value = Right(A1, Len(A1) - Len(Left(A1, InStr(A1, ",") - 1)) - 2) & " " & Left(A1, InStr(A1, ",") - 1) End If 

这将大写撇号后的下一个字符,您可以编辑它来处理其他标点符号

 Dim A1 As String A1 = Target.Value Dim i As Integer i = InStr(A1, "'") 'position of the ' If (i > 0 And Len(A1) > i) Then 'check there is a ' present and there is a character after it Target.Value = Left(A1, i) & UCase(Mid(A1, i + 1, 1)) & Right(A1, Len(A1) - i - 1) End If 

Application.EnableEvents = True行之前添加:

 If InStr(Target.Value, ",") > 0 Then Target.Value = UCase(Left(Target.Value, InStr(Target.Value, ",") - 1)) & Mid(Target.Value, InStr(Target.Value, ","), Len(Target.Value)) End If 

注意:添加With Target作为第一行代码, End With作为最后一行,并将所有Target.Value引用改为.Value
https://msdn.microsoft.com/en-us/library/wc500chb.aspx