我在Excel中使用了vba for Proper Case但是我需要为它添加一个例外规则以节省大量的手动编辑。我需要在“ - ”之后的第一个字母也是大写的,例如: “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
答案 0 :(得分:3)
以下是我Post的答案副本。它应该很适合你。
我使用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
答案 1 :(得分:2)
而不是
rng.Value = StrConv(rng.Value, vbProperCase)
使用
rng.Value = WorksheetFunction.Proper(rng.Value)
虽然这不考虑Thomas Inzina提到的don't doesn't
之类的案例。
答案 2 :(得分:1)
这是一个使用Split的小VBA功能,应该做所需的工作:
Function properCase(str As String) As String
Dim splitStr() As String
splitStr = Split(str, "-")
Dim i As Integer
For i = LBound(splitStr) To UBound(splitStr) Step 1
splitStr(i) = UCase(Left(splitStr(i), 1)) & Right(splitStr(i), Len(splitStr(i)) - 1)
Next i
properCase = Join(splitStr, "-")
End Function
答案 3 :(得分:0)
当在工作表上轻松完成时,有没有理由在VBA中执行此操作?
=PROPER("michael-jordan")
根据需要返回Michael-Jordan