VBA中的“对象variables或块variables未设置”
我正在计算使用VBA的平均值列(在wsOut)。 input在另一个工作表(wsRefor)中。
我使用下面的代码,我使用工作表函数来计算平均值
Dim Avg As Double Dim AvgRange As Range Set Reformulering = ActiveSheet For i = 1 To lastCol AvgRange = Range(wsRefor.Cells(1 + i, 4), wsRefor.Cells(1 + i, lastCol)) wsOut.Cells(i + 1, 4).Value = Application.WorksheetFunction.Average(AvgRange) Next
然而,我从for循环的第二行得到了错误:
“对象variables或块variables未设置”
我不确定我是否了解我观看的video和其他论坛讨论的错误,所以我希望任何人都可以解释或有可能指出错误
假设您定义了Dim wsRefor As Worksheet
,并将其设置为正确的工作表,然后修改您的行:
AvgRange = Range(wsRefor.Cells(1 + i, 4), wsRefor.Cells(1 + i, lastCol))
至:
Set AvgRange = wsRefor.Range(Cells(1 + i, 4), Cells(1 + i, lastCol))
或者在安全的方面:
With wsRefor Set AvgRange = .Range(.Cells(1 + i, 4), .Cells(1 + i, lastCol)) End With
编辑1 :我已经testing完整的代码(也有Average
function的error handling)
Option Explicit Sub DynamicAvgRange() Dim wsRefor As Worksheet Dim wsOut As Worksheet Dim Avg As Double Dim AvgRange As Range Dim lastCol As Long Dim i As Long Set wsRefor = ThisWorkbook.Sheets("Refor") Set wsOut = ThisWorkbook.Sheets("Out") ' just for simulating the tests lastCol = 6 For i = 1 To lastCol With wsRefor Set AvgRange = .Range(.Cells(1 + i, 4), .Cells(1 + i, lastCol)) End With If Not IsError(Application.Average(AvgRange)) Then wsOut.Cells(i + 1, 4).Value = Application.Average(AvgRange) Else ' Average value returned an error (no values in the searched range) wsOut.Cells(i + 1, 4).Value = "" ' put a blank value >> modify to your needs End If Next i End Sub
在分配对象而不是值时,您需要使用Set
关键字。
Range
是一个对象,所以它需要被Set
Set AvgRange = Range(wsRefor.Cells(1 + i, 4), wsRefor.Cells(1 + i, lastCol))
要看到区别,你可以这样做:
Dim test As Variant Range("A1").Value = "some text" test = Range("A1") '// test is now a string containing "some text" Set test = Range("A1") '// test is now a range object MsgBox test.Value '// Displays the value of the range object "some text"