我使用這個小宏將第一個字母轉換為大寫在特定範圍內:
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