excel - 运行时错误 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
解决方案
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
推荐阅读
- sql-server - 如何将 SQL 命令转换为实体框架和 Lambda 表达式
- linux - 查找上次修改时间为 8 月的文件
- spring - Spring Cloud 文件系统后端占位符不起作用
- javascript - 尝试在提交时从表单上传数据和图像
- python - 为什么在使用 py2app 编译时会收到“RecursionError:超出最大递归深度”?
- ssl - 在 SOLR 6 上设置 SSL
- git - 获取 git log 以显示给定提交的合并提交者
- node.js - Rabbitmq:发布者在 Nodejs amqplib 中确认
- javascript - Angular & Xrm WebApi:无法将结果分配给类变量
- android - 如何为 Ionic 4 android 构建设置路径变量?