我是vba的新手。单击sheet1中的按钮时,应将相关数据从sheet2带到sheet1。下面是代码。单击sheet1中的按钮时出现运行时错误,调试在第6行停止。我不确定错误在哪里。请帮忙。
1.Private Sub CommandButton1_Click()
2. a = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
3. x = 8
4. For i = 2 To a
5. If Worksheets("Sheet2").Cells(i, 3).Value = "Payments" Then
6. Worksheets("Sheet2").Range(Cells(i, "C"), Cells(i, "F")).Copy
7. Worksheets("Sheet1").Activate
8. Worksheets("Sheet1").Range(Cells(x, "D"), Cells(x, "G")).Select
9. ActiveSheet.Paste
10. x = x + 1
11. End If
Next
Application.CutCopyMode = False
ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Select
End Sub
答案 0 :(得分:0)
Private Sub CommandButton1_Click()
Dim sht2, sht1, a As Long, x As Long, i As Long
Set sht1 = Worksheets("Sheet1")
Set sht2 = Worksheets("Sheet2")
a = sht2.Cells(Rows.Count, 1).End(xlUp).Row
x = 8
For i = 2 To a
If sht2.Cells(i, 3).Value = "Payments" Then
sht2.Cells(i, "C").Resize(1, 4).Copy sht1.Cells(x, "D")
x = x + 1
End If
Next
sht1.Select
sht1.Cells(1, 1).Select
End Sub