运行时错误91对象variables或块variables未设置数据库

我有一个数据库,所有的数据都在majuscule,我想只保留这样的第一个字母,我的代码是

Sub nompropio() Dim rng As Range Dim cell As Range Set rng = Range("A1:T17058") For Each cell In rng Next cell If Not cell.HasFormula Then >>>here is the eror End If cell.Value = WorksheetFunction.Proper(cell.Value) End Sub 

我不知道是否有空白的单元格是一个问题,或者如果一些列只有数字,但没有一个单元格的公式,我只是把它放在这个例子是这样的,我试图没有这个部分,但它没有工作。

它应该使用这个语法:

 Sub nompropio() Dim rng As Range Dim cell As Range Set rng = Range("A1:T17058") For Each cell In rng If Not cell.HasFormula Then cell.Value = WorksheetFunction.Proper(cell.Value) Next End Sub 

更新后

下面的版本使用变体数组和SpecialCells比上面的范围循环版本运行相同的过程快得多。

 Sub Recut() Dim X Dim rng1 As Range Dim rng2 As Range Dim lngRow As Long Dim lngCol As Long On Error Resume Next Set rng1 = Range("A1:T17058").SpecialCells(xlConstants) On Error GoTo 0 If rng1 Is Nothing Then Exit Sub For Each rng2 In rng1.Areas If rng2.Cells.Count > 1 Then X = rng2.Value2 For lngRow = 1 To UBound(X, 1) For lngCol = 1 To UBound(X, 2) X(lngRow, lngCol) = WorksheetFunction.Proper(X(lngRow, lngCol)) Next Next rng2.Value2 = X Else rng2.Value = WorksheetFunction.Proper(rng2.Value) End If Next End Sub 

你指出的错误是因为variables超出了范围。 事实上,

  1. 在循环中,您可以隐式定义variables:

     For Each cell In rng Next cell 
  2. 在每个循环之外,您尝试调用该variables:

     If Not cell.HasFormula Then '>>>here is the error, because "cell" it's something within the previous loop, but it's nothing here so the compiler tells you "hey, I'm sorry, but I didn't set your variable". End If 

显然,variables超出了范围,因为它是在For Each循环中定义的,所以它只存在于循环范围内。 如果你想在没有公式的情况下在每个单元格上执行某些操作,那么这是正确的select:

 For Each cell In rng '<-- for each cell... If Not cell.HasFormula Then '<-- perform if the cell has no formula cell.Value = WorksheetFunction.Proper(cell.Value) '<--action to perform End If '<-- end the if-then statement Next cell '<-- go to the next cell of the range