我可以使用此宏将逗号后的首字母转换为大写吗?

我可以使用此宏将逗号后的首字母转换为大写吗?

我使用这个小宏将第一个字母转换为大写在特定范围内:

Sub TitleCase()
  Dim rng As Range, cell As Range
  Set rng = Range("D4:D999")
  For Each cell In rng
      If (cell.Value <> "") Then
          cell.Value = UCase(Left(cell.Value, 1)) & Right(cell.Value, Len(cell.Value) - 1)
      End If
  Next cell
End Sub

我现在需要将逗号 ( ,) 后的任何字母转换为大写。 如何才能做到这一点?

答案1

代替:

 cell.Value = UCase(Left(cell.Value, 1)) & Right(cell.Value, Len(cell.Value) - 1)

和:

 comma = InStr(cell.Value, ",")
 If comma <> 0 Then
    cell.Value = Left(cell.Value, comma) & UCase(Mid(cell.Value, comma + 1, 1)) & Right(cell.Value, Len(cell.Value) - comma - 1)
End If

它将转换为大写字符串中第一个逗号后的字母。


如果你有多个逗号在单元格上,用这个替换宏:

Sub TitleCase()
Dim rng As Range, cell As Range
Dim buffer() As String 'Creates an empty array
Set rng = Range("D4:D99")
For Each cell In rng
If (cell.Value <> "") Then
    buffer = Split(StrConv(cell.Value, vbUnicode), Chr$(0)) 'split characters into array
    ReDim Preserve buffer(UBound(buffer) - 1)
    iscomma = False
    changedstring = ""
    For i = LBound(buffer) To UBound(buffer)
        If iscomma = True Then
            buffer(i) = UCase(buffer(i))
            iscomma = False
        End If
        If buffer(i) = "," Then
            iscomma = True
        End If
        changedstring = changedstring & buffer(i)
    Next i
    cell.Value = changedstring
End If
Next cell
End Sub

答案2

用这个:

Private Function convertTitleToUppercase(s As String)
    Dim sSplit() As String: sSplit = Split(s, ",")
    Dim tmp As String

    Dim v As Variant: For Each v In sSplit
        tmp = IIf(tmp = "", tmp, tmp & ",") & StrConv(v, vbProperCase)
    Next v

    convertTitleToUppercase = tmp

End Function

例子:

Debug.Print convertTitleToUppercase("LANTERNE, FHIA, ANTIK MESSING")

返回:

Lanterne, Fhia, Antik Messing

相关内容