Excel 运行时错误91对象变量或未在数据库中设置块变量
我有一个数据库,所有数据都在majuscule中,我试图只保留第一个字母,我的代码是Excel 运行时错误91对象变量或未在数据库中设置块变量,excel,vba,Excel,Vba,我有一个数据库,所有数据都在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 = WorksheetFun
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
来运行相同的进程,比上面的range-loop版本快得多
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
您指示的错误是因为变量超出范围。其实,
For Each cell In rng
Next cell
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
中定义的,所以它只存在于循环的范围内。如果要在每个单元格上执行某些操作而不使用公式,那么这是正确的方法:
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
rng中每个单元格的'