"对象变量或With block变量未设置"在VBA中

时间:2016-08-31 10:14:27

标签: excel vba excel-vba

我希望使用VBA计算平均值的列(在wsOut中)。输入在另一张表格中(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-loop中的第二行得到了错误:

"对象变量或未设置块变量"

我不确定我是否理解我观看过的视频和其他论坛讨论中的错误,所以我希望任何人都可以解释或潜在地指出错误

2 个答案:

答案 0 :(得分:2)

在分配对象而不是值时,需要使用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"

答案 1 :(得分:1)

假设您定义了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 :我已经测试过的完整代码(也有Average函数的错误处理)

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