Excel 如何把文本字符串转换成适当的大小写
你有没有想过,在Excel中是否有办法自动纠正句子中字符串的大小写?在Excel中是可以实现的。本教程将帮助你了解如何在Excel中用例外情况将文本字符串转换为正确的大小写。我们可以使用VBA程序来完成这项任务,因为它不能直接在Excel中完成。当单词的字母按照语法处于正确的大小写时,它们被称为 “适当的大小写”。
在Excel中把文本字符串转换为带例外的正确大小写
在这里,我们首先要创建例外列表,然后插入VBA模块并运行它来完成任务。让我们来看看在Excel中把字符串转换为带异常的适当大小写的简单程序。
第1步
让我们考虑一个Excel工作表,其中的数据表与下图所示的数据类似。
然后右击工作表名称,选择查看代码,打开VBA应用程序。然后点击 “插入 “并选择 “模块”。
**右键单击 > 查看代码 > 插入 > 模块 **
第2步
在文本框中输入以下程序代码,如下图所示。
程序
Sub CellsValueChange()
'Update By Nirmal
Dim xSRg As Range
Dim xDRg As Range
Dim xPRg As Range
Dim xSRgArea As Range
Dim xRgVal As String
Dim xAddress As String
Dim I As Long
Dim K As Long
Dim KK As Long
On Error Resume Next
xAddress = Application.ActiveWindow.RangeSelection.Address
Set xSRg = Application.InputBox("Original cells:", "Proper Text String", xAddress, , , , , 8)
If xSRg Is Nothing Then Exit Sub
Set xDRg = Application.InputBox("Output cells:", "Proper Text String", , , , , , 8)
If xDRg Is Nothing Then Exit Sub
Set xPRg = Application.InputBox("Cells to exclude:", "Proper Text String", , , , , , 8)
If xPRg Is Nothing Then Exit Sub
Set xDRg = xDRg(1)
For I = 1 To xSRg.Areas.Count
Set xSRgArea = xSRg.Areas.Item(I)
For K = 1 To xSRgArea.Count
xRgVal = xSRgArea(K).Value
If Not IsNumeric(xRgVal) Then
xRgVal = CorrectCase(xRgVal, xPRg)
xDRg.Offset(KK).Value = xRgVal
End If
KK = KK + 1
Next
Next
End Sub
Function CorrectCase(ByVal xRgVal As String, ByVal xPRg As Range) As String
Dim xArrWords As Variant
Dim I As Integer
Dim xPointer As Integer
Dim xVal As String
xPointer = 1
xVal = xRgVal
xArrWords = WordsOf(xRgVal)
For I = 0 To UBound(xArrWords)
xPointer = InStr(xPointer, " " & xVal, " " & xArrWords(I))
Debug.Print xPointer
Mid(xVal, xPointer) = CorrectCaseOneWord(CStr(xArrWords(I)), xPRg)
Next I
CorrectCase = xVal
End Function
Function WordsOf(xRgVal As String) As Variant
Dim xDelimiters As Variant
Dim xArrRtn As Variant
xDelimiters = Array(",", ".", ";", ":", Chr(34), vbCr, vbLf)
For Each xEachDelimiter In xDelimiters
xRgVal = Application.WorksheetFunction.Substitute(xRgVal, xEachDelimiter, " ")
Next xEachDelimiter
xArrRtn = Split(Trim(xRgVal), " ")
WordsOf = xArrRtn
End Function
Function CorrectCaseOneWord(xArrWord As String, xERg As Range) As String
With xERg
If IsError(Application.Match(xArrWord, .Cells, 0)) Then
CorrectCaseOneWord = Application.Proper(xArrWord)
Else
CorrectCaseOneWord = Application.VLookup(xArrWord, .Cells, 1, 0)
End If
End With
End Function
第3步
现在将工作表保存为支持宏的工作簿,并点击F5运行代码。然后选择原始数据的范围,点击确定。
第4步
再次,选择需要输出的单元格,并点击确定。
第5步
最后,选择例外情况的范围,并点击确定。
结论
在本教程中,我们用一个简单的例子来演示如何在Excel中把文本字符串转换为带有异常的适当情况。