Ошибка 9 при выполнении макроса

Home > VBA > VBA Subscript Out of Range Runtime Error (Error 9)

Subscript Out of Range Error (Run Time: Error 9) occurs when you refer to an object or try to use a variable in a code that doesn’t exist in the code, in that case, VBA will show this error. As every code that you write is unique, so the cause of the error would be.

In the following example, you have tried to activate the “Sheet1” which is an object. But as you can see in the workbook no worksheet exists with the name “Sheet1” (instead you have “Sheet2”) so VBA show “Subscript Out of Range” to notify you that there’s something wrong with the code.

Subscript Out of Range

There could be one more situation when you have to face the error “Subscript Out of Range Error” when you are trying to declare a dynamic array but forget to use the DIM and ReDim statement to redefine the length of the array.

Now in the above code, you have an array with the name “myArray” and to make it dynamic we have initially left the array length blank. But before you add an item you need to redefine the array length using the ReDim statement.

And that’s the mistake we have made in the above code and VBA has returned the “Script Out of Range” error.

Sub myMacro()
Dim myArray() As Variant
myArray(1) = "One"
End Sub

How Do I Fix Subscript Out of Range in Excel?

The best way to deal with this Subscript Out of Range is to write effective codes and make sure to debug the code that you have written (Step by Step).

When you run a code step by step it is easy for you to know on which line of that code you have an error as VBA will show you the error message for Error 9 and highlight that line with yellow color.

The other thing that you can do is to use an “Error Handler” to jump to a specific line of error when it happens.

In the following code, we have written a line to activate the sheet but before that, we have used the goto statement to move to the error handler. In the error handler, you have a message box that shows you a message with the Err. Description that an error has occurred.

So, when you run this code and the “Sheet1” is not in the workbook where you are trying to activate it. It will show you a message box just like below.

And if the “Sheet1” is there then there won’t be any message at all.

Sub myMacro()

Dim wks As Worksheet

On Error GoTo myError
Sheets("Sheet1").Activate

myError:
MsgBox "There's an error in the code: " & Err.Description & _
". That means there's some problem with the sheet " & _
"that you want to activate"

End Sub

What is VBA

  • VBA ERROR Handling
  • VBA Automation Error (Error 440)
  • VBA Error 400
  • VBA Invalid Procedure Call Or Argument Error (Error 5)
  • VBA Object Doesn’t Support this Property or Method Error (Error 438)
  • VBA Object Required Error (Error 424)
  • VBA Out of Memory Error (Error 7)
  • VBA Overflow Error (Error 6)
  • VBA Runtime Error (Error 1004)
  • VBA Type Mismatch Error (Error 13)

 
Код
  Case x = N4 And y <> N5 ' save_3ftt_commercial_ШУЭТ
    
        Sheets(Array("АКТ", "титул", "прот6", "прот4", "паспорт-протокол", _
                     "титул БП", "прот6 БП", "прот4 БП", "паспорт-протокол БП")).Select
        Sheets("АКТ").Activate
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        ПутьКПапке & "АКТ ТО 3ф транс № " & Worksheets("титул").Range("I9"), Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
        
        Sheets(Array("СЕ308", "АТТ 1", "АТТ 2", "ВТТ 1", "ВТТ 2", "СТТ 1", "СТТ 2")).Select
        Sheets("СЕ308").Activate
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        ПутьКПапке & "АКТ ТО 3ф транс ФО № " & Worksheets("титул").Range("I9"), Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
    
    Case x = N3 And y = N5 ' save_3f_technical_ШУЭТ_УСПД_контр
    
        Sheets(Array("АКТ 1ф3ф", "титул", "прот4", "СЕ308", "титул БП", "прот4 БП")).Select
        Sheets("АКТ 1ф3ф").Activate
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        ПутьКПапке & "АКТ ТО ТехУчет № " & Worksheets("титул").Range("I9"), Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True

Добрый день!

При выполнении макроса выскакивает Run-time error 9: Элемент за пределами диапазона. Подскажите в чем может быть проблема!
Ошибка появляется в строке 11, хотя в строках 20 и 3 проблем нет . Все страницы существуют. Раньше все работало без проблем.

В строке 11 в массиве листов используются листы в, в которых вставлены графические подложки. Соответственно размер сохраненного файла *.pdf большой. Это может быть источником проблемы?

Изменено: Konstantine11.11.2017 10:15:42

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

Community's user avatar

asked Feb 20, 2014 at 22:06

user3334808's user avatar

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

answered Feb 20, 2014 at 22:10

The Dark Canuck's user avatar

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

answered Feb 20, 2014 at 22:21

Gordon Bell's user avatar

Gordon BellGordon Bell

13.2k3 gold badges45 silver badges64 bronze badges

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:

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:

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?

answered Feb 21, 2014 at 9:17

Matteo NNZ's user avatar

Matteo NNZMatteo NNZ

11.9k11 gold badges52 silver badges89 bronze badges

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate

General Philosophy Advice:

Avoid use Excel’s built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you’ll likely find that you don’t need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel’s macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

  • Remove From My Forums
  • Question

  • Hi folks,

    I am getting a run time error # 9 when I run a macro that calls a Userform or when I try to run code in a Userform module. The code performs beautifully on my computer, but it did not work on a coworker’s computer. It ended up working on 3 out of the 5 computers I have tried it on.

    I have tried changing security settings to low, and a bunch of other stuff, but I cannot get the code to run on the computers that get the run time error on them when I try running the code on them.

    I get the run time error when I try to load or show any userform in the workbook and I get it if I try to run code that is in the userform module. However, if I paste the code into a regular module and run it, the code runs fine.

    Does anyone know what could be causing this? I don’t my code is causing the problem since it runs on some machines, I am guessing there is a setting that is preventing Excel from calling Userforms. Any ideas?

    Thanks,

    Joe

Answers

  • The problem is this line in the Initialize event

    Workbooks(«TradeDB»).Activate

    The reason is works some of the time is that some of the PC have the option to hide known file extension types.

    So the file TradeDB.xls will sometimes open with that name and sometimes with just

    TradeDB.

    Including the .xls should work in either case.


    Workbooks(«TradeDB.xls»).Activate

Понравилась статья? Поделить с друзьями:
  • Ошибка 9 на iphone есть решение
  • Ошибка 9 датчик cyp цилиндра фазовый дискриминатор
  • Ошибка 9 градусов принтер hp
  • Ошибка 9 iphone 5s nand
  • Ошибка 8е1 на стиральной машине самсунг