Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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

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
like image 953
user3334808 Avatar asked Oct 28 '25 01:10

user3334808


1 Answers

"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.

like image 76
The Dark Canuck Avatar answered Oct 29 '25 16:10

The Dark Canuck