这是我编写的代码,但基本上我想将数据从一个工作表复制到另一个工作表,条件例如:“已关闭”,并且必须删除旧工作表中的行。我能够将一行复制到另一张表,但它正在复制该行4次,我无法弄清楚原因。你能看一下这段代码吗?我对VBA并不是那么先进。
Sub macro_1()
Dim lr As Long, lr2 As Long, r As Long
lr = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
lr2 = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
For r = lr To 2 Step -1
Last = Cells(Rows.Count, "G").End(xlUp).Row
For i = Last To 2 Step 1
If Range("G" & r).Value = "closed" Then
Rows(r).Copy Destination:=Sheets("Sheet2").Range("A" & lr2 + 1)
lr2 = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
End If
If (Cells(i, "G").Value) = "closed" Then 'Cells (i, "A").EntireRow.ClearContents ' USE THIS TO CLEAR CONTENTS BUT NOT DELETE ROW
Cells(i, "A").EntireRow.Delete
End If
Next i
Next r
End Sub
答案 0 :(得分:0)
您不需要第二个循环,这就是造成问题的原因。
最好始终声明对象的父级。下面的代码声明了两张纸,然后每个范围都符合正确的纸张。这样,如果由于某种原因,焦点丢失到活动工作表,则不会遇到错误。
它还可以更轻松地重命名工作表。这个名字只需要固定在一个地方而不是很多。
Sub macro_1()
Dim lr As Long, lr2 As Long, r As Long
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
lr = ws1.Cells(Rows.count, "A").End(xlUp).Row
For r = lr To 2 Step -1
lr2 = ws2.Cells(Rows.count, "A").End(xlUp).Row + 1
If ws1.Range("G" & r).value = "closed" Then
ws1.Rows(r).copy Destination:=ws2.Range("A" & lr2)
ws1.Cells(r, "A").EntireRow.Delete
End If
Next r
End Sub