Subscript out of range что значит
Перейти к содержимому

Subscript out of range что значит

Ошибка “vector subscript out of range” в цикле

код[1]

При компиляции (1) выдает (2). Что делать? Как бороться?

user avatar

Вы не можете применять оператор индексирования к вектору, который еще не имеет элементов.

Поэтому вам следует написать перед циклами

То есть сначала нужно создать элементы вектора, а затем лишь обращаться к ним по индексу.

Как вариант инициализации (при создании можешь размерность указать):

user avatar

Всё ещё ищете ответ? Посмотрите другие вопросы с метками c++ visual-c++ vector или задайте свой вопрос.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.10.42345

Нажимая «Принять все файлы cookie», вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

VBA Subscript Out of Range

Subscript out of range is an error we encounter in VBA when we try to reference something or a variable which does not exist in a code, for example, let us suppose we do not have a variable named x but we use msgbox function on x we will encounter subscript out of range error.

VBA Subscript out of range error occurs because the object we are trying to access doesn’t exist. This is an error type in VBA coding VBA Coding VBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task. read more , and this is a “Run Time Error 9”. It is important to understand the concepts to write efficient code, and it is even more important to understand the error of your VBA code Error Of Your VBA Code VBA error handling refers to troubleshooting various kinds of errors encountered while working with VBA. read more to debug the code efficiently.

If your coding error and you don’t know what that error is when you are gone.

A doctor cannot give medicine to his patient without knowing what the disease is. For sure, doctors and patients both know there is a disease (error), but it is important to understand the disease (error) than giving medicine to it. If you can understand the error perfectly, then it is much easier to find the solution.

On a similar note in this article, we will see one of the important errors we usually encounter regularity, i.e., “Subscript Out of Range” error in Excel VBA.

Table of contents

VBA Subscript Out of Range

You are free to use this image on your website, templates etc, Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Subscript Out of Range (wallstreetmojo.com)

What is Subscript out of Range Error in Excel VBA?

For example, if you are referring to the sheet which is not there is the workbook, then we get Run time error 9: “Subscript out of Range.”

Subscript out of range

If you click on the End button, it will end the subprocedure, if you click on debug, it will take you to the line of code where it encountered an error, and help will take you to the Microsoft website page.

Why Subscript Out of Range Error Occurs?

As I told as a doctor important to find the deceased before thinking about the medicine. VBA Subscript out of range error occurs when the line of code doesn’t read the object we entered.

For example, look at the below image. I have three sheets named Sheet1, Sheet2, Sheet3.

VBA Subcript Out of Range Example 1

Now in the code, I have written the code to select the sheet “Sales.”

Code:

VBA Subcript Out of Range Example 1-1

If I run this code using the F5 key or manually, I will end up getting the Run time error 9: “Subscript out of Range.”

This is because I tried accessing the worksheet object “Sales,” which does not exist in the workbook. This is a run time error because this error occurred while running the code.

Another common subscript error we get is when we refer to the workbook which is not there. For example, look at the below code.

Code:

VBA Subcript Out of Range Example 1-3

The above code says variable WB should be equal to the workbook “Salary Sheet.xlsx.” As of now, this workbook is not opened on my computer. If I run this code manually or through the F5 key, I will get Run time error 9: “Subscript out of Range.”

This is due to the workbook I am referring to, which is either not open as of now or doesn’t exist at all.

VBA Subscript Error in Arrays

When you declare the array as the dynamic array, and if you don’t use the word DIM or REDIM in VBA REDIM In VBA The VBA Redim statement increases or decreases the storage space available to a variable or an array. If Preserve is used with this statement, a new array with a different size is created; otherwise, the current variable’s array size is changed. read more to define the length of an array, we usually get VBA Subscript out of range error. For example, look at the below code.

Code:

VBA Subcript Out of Range Example 2

In the above, I have declared the variable as an array, but I have not assigned a start and ending point; rather, I have straight away assigned the first array the value of 25.

If I run this code using the F5 key or manually then, we will get Run time error 9: “Subscript out of Range.”

To fix this issue, I need to assign the length of an array by using the Redim word.

Code:

Range Example 2-2

This code does not give any errors.

How to Show Errors at the End of the VBA Code?

If you don’t want to see the error while the code is up and running but needs an error list at the end, then you need to use the “On Error Resume” error handler. Look at the below code.

Code:

Out of Range Example 3

As we have seen, this code will throw Run time error 9: “Subscript out of Range in Excel VBA. But I have to use the error handler On Error Resume Next in VBA On Error Resume Next In VBA VBA On Error Resume Statement is an error-handling aspect used for ignoring the code line because of which the error occurred and continuing with the next line right after the code line with the error. read more while running the code. We will not get any error messages. Rather at the end message box shows me the error description like this.

You can download the Excel VBA Subscript Out of Range Template here:- VBA Subscript Out of Range Template

Recommended Articles

This has been a guide to VBA Subscript Out of Range. Here we learned the Error called Subscript out of range (Run-time error’9′) in Excel VBA with along with practical examples and a downloadable template. Below you can find some useful excel VBA articles –

How to Fix ‘Subscript Out of Range’ Error in Visual Basic for Applications?

Visual Basic for Applications (VBA) is an implementation of the Visual Basic programming language developed by Microsoft. VBA can be used for enabling UDFs, automating tasks and for accessing WinAPI through DLLs. However, quite recently, a lot of reports have been coming in where users are unable to execute certain commands and a “Subscript Out of Range, Error 9” Pops up while trying to do so.

Subscript out of range error

What Causes the “Subscript Out of Range” Error in VBA?

After receiving numerous reports from multiple users, we decided to investigate the issue and devised a set of solutions to fix it completely. Also, we looked into the reasons due to which it is triggered and listed them as follows.

  • Non-Existing Element: In some cases, it is possible that you might have referenced an element in the command that doesn’t exist. It is possible that the subscript is either larger or smaller than the range of possible subscripts or dimensions might not have been assigned to the array at this point in the application.
  • Undefined Elements: It is possible that you didn’t identify the number of elements in your code, it is important that the number of elements in an array is defined by using the “Dim” or “ReDim” commands.
  • Incorrect Collection Member: In some cases, the user might have referenced a collection member that doesn’t exist. If an incorrect reference is made towards the collection member, this error might be triggered.
  • Shorthand Script: It is possible that you have made use of a shorthand form of subscript and it implicitly specified an element that was invalid. It is important to use a valid key name.

Now that you have a basic understanding of the nature of the problem, we will move on towards the solutions. Make sure to implement these in the specific order in which they are presented to avoid conflict.

Solution 1: Checking Arrays

It is possible that you have defined an incorrect value for the Array element. Therefore, it is recommended to double-check the value that you have defined for the Array element and make sure that it is the correct one. Also, make sure that you check the declaration of the array and verify the upper and the lower bounds. If the arrays have been redimensioned, make sure to use the LBound and UBound functions to condition accesses. Check the spelling of the Variable name if the index is a variable.

Array in VBA Excel

Solution 2: Specifying Number of Elements

In some cases, it is possible that you might not have defined the number of elements in your code due to which the error is being triggered. It is recommended that you specify the number of elements in the array using the Dim or ReDim functions.

Using Dim and ReDim to specify the number of elements

Solution 3: Changing Construct

This error is commonly triggered when the user specifies an incorrect or non-existent collection member. Therefore, instead of specifying the index elements, it is recommended that you approach with the “For Each…Next” construct.

Using “For Each…Next” construct

Solution 4: Checking Keyname and Index

In some cases, it is possible that you might have used a shorthand form of the subscript and it specifies an invalid element. Therefore, it is recommended that you use a valid key name and index for the collection.

Using a Valid Keyname

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *