对象变量未设置

时间:2017-01-31 16:41:20

标签: excel vba excel-vba

我一直在设置"对象变量未设置"此代码出错。我想偏移startcell单元格地址以取相应列的平均值。但是,vba尝试偏移startcell的值,而不是单元格地址。如果有人可以给我一些指导,那就太好了。谢谢!

Sub Macro1()

    Dim i As Integer
    Dim rowcount As Integer
    Dim startcell As Range

    startcell = ActiveSheet.Cells(2, 3).Address(False, False)
    rowcount = Range("C2", Range("C2").End(xlDown)).Count

    For i = 1 To rowcount
        If Not Cells(i, 3).Value = Cells(i + 1, 3).Value Then
            startcell.Offset(0, 11).Value = Application.WorksheetFunction.Average( _
            Range(startcell.Offset(0, 8), Cells(i, 11)))
            startcell = ActiveSheet.Cells(i + 1, 3).Address(False, False)
        End If
    Next i

End Sub

1 个答案:

答案 0 :(得分:3)

要在变量中保存给定范围,您可以使用其address字符串)或Range 对象。后者通常是首选,看起来这是你的意图。

Dim startcell As Range
....
Set startcell = ActiveSheet.Cells(2, 3) ' <-- Set a range object variable
....
Set startcell = ActiveSheet.Cells(i + 1, 3) ' <-- Set

另一方面,如果您想使用该地址(除非有特殊原因,否则不建议使用该地址):

Dim startAddr As String ' <--
....
startAddr = ActiveSheet.Cells(2, 3).Address(False, False) ' <-- ok, save address
....
Range(startAddr).Offset(0, 11).Value = ... ' Range(startAddr) reconstructs a range from the address
startAddr = ActiveSheet.Cells(i + 1, 3).Address(False, False)