首页 > 解决方案 > 运行时错误 1004 应用程序定义或对象定义错误

问题描述

我是 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

标签: excelvba

解决方案


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

推荐阅读