[英]Excel macro to copy range from one sheet to another
I've got a problem with copying range from one sheet to another. 我将范围从一张纸复制到另一张纸时遇到了问题。 Im trying to do it with code below 我试图用下面的代码做到这一点
Sub zaladuj()
Dim PND, DR As Worksheet
Set PND = ActiveWorkbook.Sheets("sheet2")
Set DR = ActiveWorkbook.Sheets("sheet1")
Dim row As Integer
Dim copyRng As Range, pasteRng As Range
row = 4
Do Until IsEmpty(DR.Cells(row, 2))
row = row + 1
Loop
With DR
Set copyRng = Range(Cells(3, 1), Cells(row, 5))
End With
With PND
Set pasteRng = Range(Cells(3, 1), Cells(row, 5))
End With
copyRnd.Copy pasteRng
End Sub
However after running macro, nothing happens. 但是,运行宏后,什么也没有发生。 As far as I noticed, whole functions runs only in sheet2. 据我所知,整个函数仅在sheet2中运行。 Whole macro is placed in sheet2 objects. 整个宏放置在sheet2对象中。
With
on its own does nothing. With
执行任何操作。 You need the dots in front of the rangest to tie them to the object following the With statement. 您需要在Rangest前面的点将它们与With语句之后的对象绑定在一起。
Option Explicit
Sub zaladuj()
Dim PND As Worksheet, DR As Worksheet
Set PND = ActiveWorkbook.Sheets("sheet2")
Set DR = ActiveWorkbook.Sheets("sheet1")
Dim row As Long
Dim copyRng As Range, pasteRng As Range
row = 4
Do Until IsEmpty(DR.Cells(row, 2))
row = row + 1
Loop
With DR
Set copyRng = .Range(.Cells(3, 1), .Cells(row, 5))
End With
With PND
Set pasteRng = .Range(.Cells(3, 1), .Cells(row, 5))
End With
copyRng.Copy pasteRng
End Sub
Note also that 另请注意
Dim PND, DR As Worksheet
declares PND
as Variant
- see amendment above. 宣布PND
为Variant
-参见上述修订。
Use Long
rather than Integer
as Excel has many more rows than Integer
can handle. 使用Long
而不是Integer
因为Excel具有比Integer
可以处理的更多的行。
You can probably replace with your Do
loop with 您可能可以用Do
循环替换为
row=DR.Cells(rows.count, 2).end(xlup).row
Is this what to do expect? 这是该期待的吗?
EDITED CODE 编辑代码
Option Explicit
Sub zaladuj()
Dim PND As Worksheet, DR As Worksheet
Dim row As Long
With ThisWorkbook
Set DR = .Sheets("Sheet1")
Set PND = .Sheets("Sheet2")
End With
row = 4
Do Until IsEmpty(DR.Cells(row, 2))
DR.Range(DR.Cells(3, 1), DR.Cells(row, 5)).Copy PND.Range(PND.Cells(3, 1), PND.Cells(row, 5))
row = row + 1
Loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.