vba 宏运行时错误“9”:下标超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21920697/
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-08 17:49:43  来源:igfitidea点击:

macro run-time error '9': subscript out of range

excelexcel-vbavba

提问by user3334808

I found a macro on the web to protect a worksheet with a password. It works fine, but when I save the file I get the message: run-time error '9': subscription out of range. I have never programmed or used visual basic before and could use some help . Thank you

我在网上找到了一个宏来用密码保护工作表。它工作正常,但是当我保存文件时,我收到消息:运行时错误“9”:订阅超出范围。我以前从未编程或使用过visual basic,可以使用一些帮助。谢谢

The macro is:

宏是:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

'Step 1:Protect the sheet with a password
    Sheets("Sheet1").protect Password:="btfd"

'Step 2: Save the workbook
    ActiveWorkbook.Save
End Sub

回答by The Dark Canuck

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

“下标超出范围”表示您试图从不存在的集合中访问元素。您的工作簿中是否有“Sheet1”?如果没有,您需要将其更改为要保护的工作表的名称。

回答by Gordon Bell

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

为什么要使用宏?Excel 内置了密码保护功能。当您选择文件/另存为...时,保存按钮旁边应该有一个工具按钮,单击它,然后单击“常规选项”,您可以在其中输入“打开密码”和“修改密码”。

回答by Matteo NNZ

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

当您收到错误消息时,您可以选择单击“调试”:这将引导您到发生错误的行。Dark Canuck 好像是对的,我猜错误发生在线路上:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

因为很可能“Sheet1”不存在。但是,如果您说“它工作正常,但是当我保存文件时,我收到消息:运行时错误'9':订阅超出范围”,这让我认为错误发生在第二行:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

您可以先按“调试”按钮来检查一下吗?最重要的是,正如 Gordon Bell 所说,为什么要使用宏来保护工作簿?