Word VBA 宏将选定的文本转换为标题大小写,忽略冒号后面的“例外”词

Word VBA 宏将选定的文本转换为标题大小写,忽略冒号后面的“例外”词

为了将 Microsoft Word 中选定的文本转换为标题大小写,我发现了以下有用的宏:word 2010 中标题大小写的键盘快捷键

我想知道是否有办法修改宏,以便它始终将冒号后面的单词大写,即使该单词在“例外”列表中(例如,and、of、in、the)。

Sub TitleCase()
Dim lclist As String
Dim wrd As Integer
Dim sTest As String

' list of lowercase words, surrounded by spaces
lclist = " of the by to is from a and but as at in "

Selection.Range.Case = wdTitleWord

For wrd = 2 To Selection.Range.Words.Count
    sTest = Trim(Selection.Range.Words(wrd))
    sTest = " " & LCase(sTest) & " "
    If InStr(lclist, sTest) Then
        Selection.Range.Words(wrd).Case = wdLowerCase
    End If
Next wrd
End Sub

例如,如果选择了以下文本,“这是我的标题:副标题放在这里”,结果将是:“这是我的标题:此处放置字幕”,尽管“the”在例外列表中。

答案1

我修改了你的代码,这样它就会忽略冒号后面的单词。

Sub TitleCase()
Dim lclist As String
Dim wrd As Integer
Dim sTest As String
Dim skipNext As Boolean

' list of lowercase words, surrounded by spaces
lclist = " of the by to is from a and but as at in "

Selection.Range.Case = wdTitleWord

For wrd = 2 To Selection.Range.words.Count
    sTest = Trim(Selection.Range.words(wrd))
    Select Case sTest
        Case ":"
            skipNext = True
        Case Else
            If skipNext = True Then
                skipNext = False
            Else
                sTest = " " & LCase(sTest) & " "
                If InStr(lclist, sTest) Then
                    Selection.Range.words(wrd).Case = wdLowerCase
                End If
            End If
    End Select
Next wrd
End Sub

相关内容