2016-07-25 52 views

回答

1

以下VBA代码将是良好的开端

Option Base 1 
Option Explicit 

Function ProperIsh(inputString As String) As String 
    Dim result As String 
    Dim currWord As String 
    Dim idx As Integer 
    Dim wordPos As Integer 

    ' List of words to revert to lower-case ' 

    Dim lowerWords As Variant 
    lowerWords = Array("Of", "And", "It", "For", "Am", "The") 

    ' Get proper-cased string with spaces on either end ' 

    result = " " & WorksheetFunction.Proper(inputString) & " " 

    ' Process each word to revert to lower-case ' 

    For idx = 1 To UBound(lowerWords) 
     ' Revert every one of that word with spaces on either side ' 

     currWord = " " & lowerWords(idx) & " " 
     wordPos = InStr(result, currWord) 
     While wordPos > 0 
      result = Left(result, wordPos - 1) & LCase(currWord) & Mid(result, wordPos + Len(currWord)) 
      wordPos = InStr(result, currWord) 
     Wend 
    Next 

    ' Get rid of the spaces at the end ' 

    ProperIsh = Mid(result, 2, Len(result) - 2) 
End Function 

而对于它的一些测试代码:

Sub test() 
    MsgBox (ProperIsh("HELLO I AM THE LAW and i am the lower case law of everything")) 
End Sub 

它所做的是正确的情况下的每一个字(大写首字母,其他的一切小写),然后系统恢复任何特殊的词语都会回到所有的低位ER-情况。

它假设空间是唯一的分隔符,但如果是这样的话可以使其更具适应性。

测试代码生成一个消息框与预期的输出:

Hello I am the Law and I am the Lower Case Law of Everything 

为了使用它在表达式中,把它作为任何其它用户定义的函数,例如具有:

=ProperIsh(A1) 

您可以在运行中看到它,其中列B使用上面显示的公式:

   A       B 
1 director of medicine  Director of Medicine 
2 I am the law    I am the Law 
3 Let slip the dogs of war Let Slip the Dogs of War 
+1

当使用-ish作为后缀时,不需要大写; D –

0

我用Rules for Capitalization in Titles of Articles作为创建大写异常列表的参考。

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 
相关问题