范围错误的参数数量或无效的属性分配

我试图将选定的单元格复制到另一个工作表,但我总是收到错误消息:错误数量的参数或无效的属性分配

此代码检查“Cells(i,20)”小于还是大于“Cells(i,4)”10%。 如果不是,则删除该行,如果是,则应将所选单元格复制到另一个从第48行开始的表格。

也许有人可以指出,我在这里做错了什么? 以下是我的代码的样子:

Sub CopyHighLow() Sheets("ProductionHighLow").Select i = 2 j = 48 produced = 0 While Cells(i, 1) <> "" Or Cells(i + 1, 1) <> "" produced = Cells(i, 20) ordered = Cells(i, 4) If Cells(i, 20) > Cells(i, 4) * 0.9 And Cells(i, 20) < Cells(i, 4) * 1.1 Then Cells(i, 22).Delete Shift:=xlUp i = i - 1 Else Range(Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4), Cells(i, 20)).Select Selection.Copy Destination:=Sheets("Rytinis").Range(Cells(j, 1), Cells(j, 2), Cells(j, 3), Cells(j, 4), Cells(j, 5)) j = j + 1 End If i = i + 1 Wend End Sub 

更新这里是工作修改版本:

 Sub CopyHighLow() Sheets("ProductionHighLow").Select i = 2 j = 48 produced = 0 While Cells(i, 1) <> "" Or Cells(i + 1, 1) <> "" produced = Cells(i, 20) ordered = Cells(i, 4) If Cells(i, 20) > Cells(i, 4) * 0.9 And Cells(i, 20) < Cells(i, 4) * 1.1 Then Cells(i, 22).Delete Shift:=xlUp i = i - 1 Else Set RangeUnionCopy = Union(Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4), Cells(i, 20)) Set RangeUnionPaste = Union(Cells(j, 1), Cells(j, 2), Cells(j, 3), Cells(j, 4), Cells(j, 5)) RangeUnionCopy.Copy Destination:=Sheets("Rytinis").Range(RangeUnionPaste.Address) j = j + 1 End If i = i + 1 Wend End Sub 

问题解释
你的问题依赖于这一行

 Range(Cells(j, 1), Cells(j, 2), Cells(j, 3), Cells(j, 4), Cells(j, 5)) 

Range对象不能处理两个以上的命名单元格(这种方式)。 你可以直接在编译器中看到它。

在这里输入图像说明

更多信息在它的官方文档

解决scheme:
在此之前我会使用Union,就像这样:

 Set RangeUnion = Union(Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4), Cells(i, 20)) RangeUnion.Copy Destination:=Sheets("Rytinis").Range(RangeUnion.Address) 

这应该适合你的目标。

更正使用Union的代码:

 Sub CopyHighLow() Dim i, j, produced, ordered Sheets("ProductionHighLow").Select i = 2 j = 48 produced = 0 While Cells(i, 1) <> "" Or Cells(i + 1, 1) <> "" produced = Cells(i, 20) ordered = Cells(i, 4) If Cells(i, 20) > Cells(i, 4) * 0.9 And Cells(i, 20) < Cells(i, 4) * 1.1 Then Cells(i, 22).Delete Shift:=xlUp i = i - 1 Else Union(Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4), Cells(i, 20)).Select Selection.Copy Destination:=Sheets("Rytinis").Cells(j, 1) j = j + 1 End If i = i + 1 Wend End Sub 

你需要告诉它从哪个表复制。

 Sub CopyHighLow() Sheets("ProductionHighLow").Select i = 2 j = 48 produced = 0 While Cells(i, 1) <> "" Or Cells(i + 1, 1) <> "" produced = Cells(i, 20) ordered = Cells(i, 4) If Cells(i, 20) > Cells(i, 4) * 0.9 And Cells(i, 20) < Cells(i, 4) * 1.1 Then Cells(i, 22).Delete Shift:=xlUp i = i - 1 Else ActiveSheet.Range(Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4), Cells(i, 20)).Select Selection.Copy Destination:=Sheets("Rytinis").Range(Cells(j, 1), Cells(j, 2), Cells(j, 3), Cells(j, 4), Cells(j, 5)) j = j + 1 End If i = i + 1 Wend End Sub