为什么我的VBA excel表没有复制?

时间:2011-08-09 21:00:03

标签: excel vba

我是新手,不知道为什么我的工作表没有复制到新工作表上?我在VBA中找不到错误。

Private Sub Adminminreport_Click()

Application.ScreenUpdating = False

Dim i&, LR&, count&

LR = Worksheets("Parts").Range("J" & Rows.count).End(xlUp).Row
Set newWS = Worksheets.Add

Worksheets("Parts").Range(Worksheets("Parts").Cells(1, 1), Worksheets("Parts").Cells(1, 13)).Copy newWS.Range("A1")
count = 2

For i = 2 To LR
    If Range("J" & i).Value < Range("L" & i).Value Then
        Worksheets("Parts").Range(Worksheets("Parts").Cells(i, 1), Worksheets("Parts").Cells(i, 13)).Copy newWS.Range("A" & count)
        count = count + 1
    End If
Next i

Application.ScreenUpdating = True

Unload Me

newWS.Activate

End Sub

1 个答案:

答案 0 :(得分:2)

始终使用其父工作表限定Range对象是一种好习惯。否则,当您的代码运行时,您依赖于某个工作表处于活动状态...

Private Sub Adminminreport_Click()

   Dim i As Long, LR As Long, count As Long
   Dim newWS As Worksheet, partsWS As Worksheet

   Set newWS = Worksheets.Add()
   Set partsWS = Worksheets("Parts")

   Application.ScreenUpdating = False

   LR = partsWS.Range("J" & Rows.count).End(xlUp).Row
   Range(partsWS.Cells(1, 1), partsWS.Cells(1, 13)).Copy _
                                     newWS.Range("A1")
   count = 2

   For i = 2 To LR
    If partsWS.Range("J" & i).Value < partsWS.Range("L" & i).Value Then
         Range(partsWS.Cells(i, 1), partsWS.Cells(i, 13)).Copy _
                                    newWS.Range("A" & count)
         count = count + 1
    End If
   Next i

   Application.ScreenUpdating = True

   newWS.Activate
   Unload Me

End Sub