新手:在工作表中设置范围对象时出错

时间:2018-05-01 14:45:36

标签: excel vba

我是VBA领域的新手,我想知道为什么下面这行代码不起作用?

我收到错误1004:对象工作表范围失败

Sub MMMatch()
Dim oCell as Range
Dim r_out as Range
Dim r_in as Range
Dim ws1 as worksheet
Dim ws2 as worksheet

Set ws1 = Worksheets("MM Limits")
Set ws2= Worksheets("PivotTable")

Set r_out= ws1.range(Range("A2"),Range("A2").endxldown)
Set r_in=ws2.range(range("D2"),range("D2").endxldown)

end sub

我在最后一行收到错误。虽然我可以在设置范围对象之前添加代码行来首先选择工作表,但我想知道为什么这行代码不起作用?

1 个答案:

答案 0 :(得分:0)

您必须将所有Range对象限定为其父表单,Endxldown应为End(xlDown)

Sub MMMatch()
Dim oCell As Range
Dim r_out As Range
Dim r_in As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Worksheets("MM Limits")
Set ws2 = Worksheets("PivotTable")
'the Ranges inside the outer range must match the parent sheet
Set r_out = ws1.Range(ws1.Range("A2"), ws1.Range("A2").End(xlDown))
Set r_in = ws2.Range(ws2.Range("D2"), ws2.Range("D2").End(xlDown))

End Sub