Proper Case with extra rules in Excel

前端 未结 4 1086
闹比i
闹比i 2021-01-25 00:19

I have used vba for Proper Case in Excel but I need to add an exception rule for it to save much manual editing. I need the first letter after \"-\" to also be Capitalized, exam

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-25 00:59

    Here is a copy of my answer from this Post. It should work nicely for you.

    I used Rules for Capitalization in Titles of Articles as a reference to create a capitalization exceptions list.

    Function TitleCase uses WorksheetFunction.ProperCase to preproccess the text. For this reason, I put in an exception for contractions because WorksheetFunction.ProperCase improperly capitalizes them.

    The first word in each sentence and the first word after a double quotation mark will remain capitalized. Punctuation marks are also handled properly.

    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
    

提交回复
热议问题