在Excel中正确的个案select

我有一些代码应该将我的文本转换为正确的情况下,但它不工作。 我开始标记我想要转换的单元格,然后运行此macros:

Sub ProperCase() Dim rng As Range, cell As Range Set rng = Selection For Each cell In rng Next cell cell.Value = WorksheetFunction.Proper(cell.Value) End Sub 

但Excel给了我runtimer错误91

对象variables或未设置块variables

你的代码将覆盖公式 – 告诉它忽略公式。
而不是使用WorksheetFunction.Proper使用StrConv(value, conversion_type)

 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 StrConv(rng.Value, vbLowerCase) 'Ensure all exception words are lower case. Case "bob", "word2", "dave", "some other words" 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 

编辑:添加SELECT...CASE按照评论排除单词。

cell.value应该在迭代到下一个单元格之前:

 Sub ProperCase() Dim rng As Range, cell As Range Set rng = Selection For Each cell In rng cell.Value = WorksheetFunction.Proper(cell.Value) Next cell End Sub