vba 尝试复制工作表时出现运行时错误“424”“需要对象”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27543679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:33:56  来源:igfitidea点击:

Run-time error '424' "object required" when trying to copy sheet

vbaexcel-vbaexcel

提问by user1544327

I get this error on the line indicated below. What am I doing wrong?

我在下面指示的行上收到此错误。我究竟做错了什么?

Run-time error '424' object required

需要运行时错误“424”对象

Sub GetSheets()
Path = "C:\Users\vinod\Desktop\dt kte\"
Filename = Dir(Path & "*.xls")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
Sheets("Payout Summary").Select
Sheet.Copy After:=ThisWorkbook.Sheets(1) ' <~~~~ Error occurs here
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub

回答by Jean-Fran?ois Corbett

The error occurs because Sheetis NothingEmpty. You haven't declared any variable Sheet; when you use it for the first time, it defaults to a Variant whose value is Empty.

发生错误的原因SheetNothingEmpty。您尚未声明任何变量Sheet;当您第一次使用它时,它默认为一个值为空的 Variant。

Change the faulty line to:

将故障线路改为:

ActiveSheet.Copy After:=ThisWorkbook.Sheets(1) 

Though really, you should read this: How to avoid using Select in Excel VBA macros

虽然真的,你应该阅读这个:如何避免在 Excel VBA 宏中使用选择

And also use Option Explicitat the top of your modules to force yourself to declare all variables explicitly. Had you done that, you would have been able to find your error much more quickly.

并且还在Option Explicit模块顶部使用强制自己显式声明所有变量。如果您这样做了,您将能够更快地找到您的错误。

回答by Gene Skuratovsky

a small improvement on Jean-Fran?ois Corbett's answer:

Jean-Fran?ois Corbett 的回答的一个小改进:

replace the lines

更换线条

Sheets("Payout Summary").Select
Sheet.Copy After:=ThisWorkbook.Sheets(1)

with

Sheets("Payout Summary").Copy After:=ThisWorkbook.Sheets(1)

You do not need to "Select"!!! You, apparently recorded a Macro and are kind of duplicating it. Macros are there to just to look at and improve upon :)

你不需要“选择”!!!你,显然录制了一个宏并且有点复制它。宏只是为了查看和改进:)