Excel VBA正确,有例外

时间:2016-09-29 08:08:40

标签: excel vba excel-vba

我使用此代码将名称转换为Proper Case,但“von”,“af”,“de”除外。但它不起作用,因为这些名字通常是“von Erik”或“af John”而不仅仅是“von”或“af”。我怎样才能让excel得到这个?

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 = WorksheetFunction.Proper(rng.Value)
        End Select
    Next rng

End Sub

1 个答案:

答案 0 :(得分:0)

您可以将整个单元转换为Proper Case,然后运行三重替换功能来替换您单词的任何正确案例版本:

Sub ProperCase()

Dim rng As Range

'Use special cells so as not to overwrite formula.
For Each rng In Selection.SpecialCells(xlCellTypeConstants, xlTextValues).Cells
    rng.Value = StrConv(rng.Value, vbProperCase)
    rng.Value = Replace(Replace(Replace(rng.Value, "Von", "von"),"Af","af"), "De", "de")
Next rng

End Sub