Excel 中带有额外规则的正确大小写

Her*_*esh 1 excel vba

我已在 Excel 中使用 vba 进行正确大小写,但我需要为其添加例外规则以节省大量手动编辑。我需要“-”之后的第一个字母也大写,例如:当我运行脚本时,“michael-jordan”现在变成“Michael-jordan”。我需要“michael-jordan”才能成为“Michael-Jordan”。

这是我的代码:我的代码中还有“von”、“af”和“de”的例外情况。

Sub ProperCase()

Dim rng As Range

'Use special cells so as not to overwrite formula.
For Each rng In Selection.SpecialCells(xlCellTypeConstants, xlTextValues).Cells
    Select Case rng.Value
        Case "von", "af", "de"
            rng.Value = StrConv(rng.Value, vbLowerCase)
        Case Else
            'StrConv is the VBA version of Proper.
            rng.Value = StrConv(rng.Value, vbProperCase)
    End Select
Next rng

End Sub
Run Code Online (Sandbox Code Playgroud)

小智 5

这是我在这篇文章中的回答的副本。它应该很适合你。

我使用文章标题中的大写规则作为参考来创建大写例外列表。

Function TitleCase用于WorksheetFunction.ProperCase预处理文本。出于这个原因,我为收缩设置了一个例外,因为WorksheetFunction.ProperCase它们的大写方式不正确。

每个句子中的第一个单词和双引号后的第一个单词将保持大写。标点符号也处理得当。

Function TitleCase(text As String) As String
    Dim doc
    Dim sentence, word, w
    Dim i As Long, j As Integer
    Dim arrLowerCaseWords

    arrLowerCaseWords = Array("a", "an", "and", "as", "at", "but", "by", "for", "in", "of", "on", "or", "the", "to", "up", "nor", "it", "am", "is")

    text = WorksheetFunction.Proper(text)

    Set doc = CreateObject("Word.Document")
    doc.Range.text = text

    For Each sentence In doc.Sentences
        For i = 2 To sentence.Words.Count
            If sentence.Words.Item(i - 1) <> """" Then
                Set w = sentence.Words.Item(i)
                For Each word In arrLowerCaseWords
                    If LCase(Trim(w)) = word Then
                        w.text = LCase(w.text)
                    End If

                    j = InStr(w.text, "'")

                    If j Then w.text = Left(w.text, j) & LCase(Right(w.text, Len(w.text) - j))

                Next
            End If
        Next
    Next

    TitleCase = doc.Range.text

    doc.Close False
    Set doc = Nothing
End Function
Run Code Online (Sandbox Code Playgroud)