Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 运行时错误91对象变量或未在数据库中设置块变量_Excel_Vba - Fatal编程技术网

Excel 运行时错误91对象变量或未在数据库中设置块变量

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

我有一个数据库,所有数据都在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
来运行相同的进程,比上面的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中每个单元格的
    '