使用 VBA 代码更改文本大小写此方法提供了四种 VBA 代码,帮助您将指定范围内的文本大小写更改为大写、小写、首字母大写和句子大小写。请按照以下步骤操作并选择您需要的代码。
步骤 1:打开 Microsoft Visual Basic for Applications 窗口
按 Alt + F11 键打开此窗口。
步骤 2:插入模块并输入 VBA 代码
点击 插入 > 模块,然后复制并粘贴以下 VBA 代码之一到模块(代码)窗口中。
在这种情况下,我想将范围内的文本大小写更改为大写,因此我将复制并粘贴以下 VBA 代码 1。
VBA 代码 1:将范围内的文本大小写更改为大写
Sub ChangeToUppercase()
'Updated by Extendoffice 20230913
Dim rng As Range, cell As Range
On Error Resume Next
Set rng = Application.InputBox("Please select a range", "KuTools For Excel", Type:= 8)
On Error GoTo 0
If Not rng Is Nothing Then
For Each cell In rng.Cells
cell.Value = UCase(cell.Value)
Next cell
End If
End SubVBA 代码 2:将范围内的文本大小写更改为小写
Sub ChangeToLowercase()
'Updated by Extendoffice 20230913
Dim rng As Range, cell As Range
On Error Resume Next
Set rng = Application.InputBox("Please select a range", "KuTools For Excel", Type:= 8)
On Error GoTo 0
If Not rng Is Nothing Then
For Each cell In rng.Cells
cell.Value = LCase(cell.Value)
Next cell
End If
End SubVBA 代码 3:将范围内的文本大小写更改为首字母大写
Sub ChangeToPropercase()
'Updated by Extendoffice 20230913
Dim rng As Range, cell As Range
Dim vText As Variant, i As Long
On Error Resume Next
Set rng = Application.InputBox("Please select a range", "KuTools For Excel", Type:= 8)
On Error GoTo 0
If Not rng Is Nothing Then
For Each cell In rng.Cells
vText = Split(cell.Value, " ")
For i = LBound(vText) To UBound(vText)
vText(i) = Application.WorksheetFunction.Proper(vText(i))
Next i
cell.Value = Join(vText, " ")
Next cell
End If
End SubVBA 代码 4:将范围内的文本大小写更改为句子大小写
Sub ChangeToSentenceCase()
'Updated by Extendoffice 20230913
Dim rng As Range, cell As Range
Dim content As String
On Error Resume Next
Set rng = Application.InputBox("Please select a range", "KuTools For Excel", Type:= 8)
On Error GoTo 0
If Not rng Is Nothing Then
For Each cell In rng.Cells
content = LCase(cell.Value)
cell.Value = UCase(Left(content, 1)) & Mid(content, 2)
Next cell
End If
End Sub步骤 3:运行 VBA 代码
按 F5 键运行代码。然后将出现一个对话框,提示您选择包含要更改大小写的文本的单元格(这里我选择范围 A2:A7)。做出选择后,点击确定。
结果
所选单元格中的文本随后更改为大写或您指定的大小写。