Yu_na 0 / 0 / 0 Регистрация: 18.10.2011 Сообщений: 5 |
||||
1 |
||||
15.11.2011, 17:21. Показов 18297. Ответов 2 Метки нет (Все метки)
Здравствуйте, прошу помочь — при запуске программы возникает ошибка «Subscript out of range » на строке f(i) = Mid(alf, i, 1). В чём причина?
0 |
Lubocka |
|
15.11.2011, 19:52 |
2 |
Если Вы хотите применять динамический массив, почитайте это: Dim MyArray () AS Integer ReDim [Preserve] ИмяМассива(НомерПоследнегоЭлемента) Оператор ReDim можно применять многократно к одному и тому же динамическому массиву. По умолчанию после каждого применения этого оператора хранившиеся в массиве данные пропадают, поскольку массив переинициализируется. Избежать этого можно, применив в операторе ReDim необязательное ключевое слово Preserve. В этом случае массив не будет повторно инициализироваться. Естественно, ключевое слово Preserve имеет смысл применять к имени динамического массива, только начиная со второго применения оператора ReDim. Кроме того, на применение этого ключевого слова накладывается еще несколько ограничений. |
0 / 0 / 0 Регистрация: 18.10.2011 Сообщений: 5 |
|
15.11.2011, 20:10 [ТС] |
3 |
Благодарю, разобралась.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
15.11.2011, 20:10 |
Помогаю со студенческими работами здесь ‘Runtime error ‘9’: Subscript out of range’ Word: Error — Subscript Out of Range Error 9: Subscript out of range — VBA Sub задача() Run-time error ‘9’: Subscript out of range Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 3 |
-
#2
Re: VAB Redim Preserve subscript out of range
You can only redim preserve the last dimension of the array. You’re trying to resize the first
-
#3
Re: VAB Redim Preserve subscript out of range
Ah, i figured since there was only 1 column it would be both the first and the last.
How do i make it redim the last dimension?
RoryA
MrExcel MVP, Moderator
-
#4
Re: VAB Redim Preserve subscript out of range
You can’t change the number of dimensions. You’d have to create a new array and populate it in a loop.
-
#5
Re: VAB Redim Preserve subscript out of range
Thanks both, here’s what i’ve done:
Code:
avarData = dic.keys
k = UBound(avarData, 1)
ReDim NewList(1 To k, 1 To 3)
For b = 1 To k
NewList(b, 1) = avarData(b)
NewList(b, 2) = avarData(b)
NewList(b, 3) = avarData(b)
Next b
PS i’m aware that this is replicated 3 identical columns..
-
#6
Re: VAB Redim Preserve subscript out of range
Hi
Remark:
You may already have taken care of it, but dic.keys will return a zero based array by default.
-
#7
Re: VAB Redim Preserve subscript out of range (sorted)
Hi pgc01, is that why my code is cutting off the first value? I’ve tried all ways to amend it, but cant seem to get it sorted. Here’s what i’ve got:
Code:
avarData = dic.keys
k = UBound(avarData, 1)
ReDim NewList(1 To k, 1 To 6)
For b = 1 To k
NewList(b, 1) = avarData(b)
NewList(b, 2) = Application.WorksheetFunction.Index(Sheets("Barrels").Range("D:D"), Application.WorksheetFunction.Match(avarData(b), Sheets("Barrels").Range("E:E"), 0))
NewList(b, 3) = avarData(b)
NewList(b, 4) = avarData(b)
NewList(b, 5) = Format(DateAdd("m", -12, ComboBox1.Value), "MMM YY")
NewList(b, 6) = Format(Application.WorksheetFunction.SumIfs(Sheets("Barrels").Range("I:I"), Sheets("Barrels").Range("H:H"), Format(DateAdd("m", -12, ComboBox1.Value), "MMM YY"), Sheets("Barrels").Range("E:E"), avarData(b)), "0.0")
Next b
Me.ListBox1.List = NewList
EDIT — Sorted! Changed for 1 to k to for 0 to k
Last edited: Oct 30, 2017
-
#8
Re: VAB Redim Preserve subscript out of range (sorted)
Hi pgc01, is that why my code is cutting off the first value?
Yes it is (was) but I see you’ve solved the problem.
Another way would be to set the option base 1, but that would impact all other arrays in the module.
-
#9
Re: VAB Redim Preserve subscript out of range
You can’t change the number of dimensions. You’d have to create a new array and populate it in a loop.
If there are less than 65,536 elements in the array, you could also do it this way…
Code:
k = UBound(avarData, 1)
avarData = Application.Transpose(avarData)
ReDim avarData(1 To k, 1 To UBound(avarData, 1))
avarData = Application.Transpose(avarData)
I am not sure how efficient one of these methods are compared to the other, but I thought I would offer it as an alternative.
Subscript out of range is an error we encounter in VBA when we try to reference something or a variable that does not exist in a code. For example, suppose we do not have a variable named x. Then, if we use the MsgBox function on x, we will encounter a “Subscript out of range” error.
VBA “Subscript out of range” error occurs because the object we are trying to access does not exist. It is an error type in VBA codingVBA 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, a “Run Time Error 9.” It is important to understand the concepts to write efficient code. It is even more important to understand the error of your VBA codeVBA error handling refers to troubleshooting various kinds of errors encountered while working with VBA. read more to debug the code efficiently.
If you make a coding error and do not know what that error is when you are gone.
A doctor cannot give medicine to his patient without knowing what the disease is. Doctors and patients both know there is a disease (error), but it is more important to understand the disease (error) rather than give medicine to it. If you can understand the error perfectly, it is much easier to find the solution.
Similarly, this article will see one of the important errors we regularly encounter, i.e., the “Subscript out of range” error in Excel VBA.
Table of contents
- Excel VBA Subscript Out of Range
- What is Subscript out of Range Error in Excel VBA?
- Why Subscript Out of Range Error Occurs?
- VBA Subscript Error in Arrays
- How to Show Errors at the End of the VBA Code?
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle 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, not the workbook, then we get Run-time error ‘9’: “Subscript out of range.”
If you click on the “End” button, it will end the sub procedure. 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 Does Subscript Out of Range Error Occur?
As we said, as a doctor, it is important to find the deceased before thinking about the medicine. VBA “Subscript out of range” error occurs when the line of code does not read the object we entered.
For example, look at the below image. We have three sheets: Sheet1, Sheet2, and Sheet3.
Now in the code, we have written the code to select the sheet “Sales.”
Code:
Sub Macro2() Sheets("Sales").Select End Sub
If we run this code using the F5 key or manually, we will get the Run-time error ‘9’: “Subscript out of range.”
It is because we tried accessing the worksheet object “Sales,” which does not exist in the workbook. It is a run time error because it occurred while running the code.
Another common subscript error is when we refer to the workbook, which is not there. For example, look at the below code.
Code:
Sub Macro1() Dim Wb As Workbook Set Wb = Workbooks("Salary Sheet.xlsx") End Sub
The above code says variable WB should be equal to the workbook “Salary Sheet.xlsx.” As of now, this workbook is not open on the computer. If we run this code manually or through the F5 key, we will get Run time error 9: “Subscript out of Range.“
It is due to the workbook we are referring to which is either not open or does not 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 VBAThe 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 the VBA “Subscript out of range” error. For example, look at the below code.
Code:
Sub Macro3() Dim MyArray() As Long MyArray(1) = 25 End Sub
In the above, we have declared the variable as an array but have not assigned a start and ending point. Rather, we have assigned the first array the value of 25.
If we run this code using the F5 key or manually, we will get Run time error ‘9’: “Subscript out of Range.”
To fix this issue, we need to assign the length of an array by using the “ReDim” word.
Code:
Sub Macro3() Dim MyArray() As Long ReDim MyArray(1 To 5) MyArray(1) = 25 End Sub
This code does not give any errors.
How to Show Errors at the End of the VBA Code?
If you do not 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. For example, look at the below code.
Code:
Sub Macro1() Dim Wb As Workbook On Error Resume Next Set Wb = Workbooks("Salary Sheet.xlsx") MsgBox Err.Description End Sub
As we have seen, this code will throw Run time error 9: “Subscript out of range” in Excel VBA. But we must use the error handler On Error Resume Next in VBAVBA 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. So, we will not get any error messages. Rather, 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 article 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, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –
- Declare Global Variables in VBA
- VBA AutoFill
- Clear Contents in VBA
- Excel VBA UCase Function
Selected Answer
Hello Kalil,
I think the error has to do with a missing reset of the array FileList(). I added that and changed the indexing of the array at the same time so that the index number in the array coincides with the row number in the ActiveSheet.
Sub RenameFiles5()
' 275
Const MYPATH As String = "C:UsersLP PCDesktopfl"
Dim Ws As Worksheet
Dim LastCol As Long, LastRow As Long
Dim R As Long, C As Long ' rows and columns should be Long integers
Dim NewName As String, FileExt As String, OldName As String
Dim FileName As String, FileList() As String, i As Integer
Set Ws = ActiveSheet ' dangerous! replace with Worksheets("Tab name")
LastCol = Ws.Cells(1, Ws.Columns.Count).End(xlToLeft).Column
For C = 1 To LastCol
FileExt = Ws.Cells(1, C).Value
ReDim FileList(2 To 1000)
i = 1
FileName = Dir(MYPATH & FileExt & "")
While Len(FileName) > 1
i = i + 1
FileList(i) = FileName
FileName = Dir()
Wend
If i > 1 Then
ReDim Preserve FileList(2 To i)
LastRow = Ws.Cells(Ws.Rows.Count, C).End(xlUp).Row
For R = 2 To LastRow
OldName = MYPATH & FileExt & "" & FileList(R)
NewName = MYPATH & FileExt & "" & Ws.Cells(R, C).Value & "." & FileExt
Name OldName As NewName
Next R
End If
Next C
MsgBox "Done!"
End Sub
Your original code oscillates between using the ActiveSheet by name and by default. Using it be name should be restricted to when it doesn’t have a name. This only happens when a new sheet is created by code. Using it by default isn’t good practice because you can never be sure which sheet the user activated unless you call the code with a button. But to use both by name and by default in one procedure intends to confuse the programmer, and that is never a good idea.
Another thing you might like to learn is that when you use Redim Preserve VBA will create a completely new array, transferring all values from the previous to the new, one by one. That is time consuming and should therefore be avoided doing in a loop. It’s better to declare the array as too large initially and then redim it only once the required number of elements is known. I have implemented this method in your code. I allowed for 1000 files. You can increase that number without ill effect.
Lolik Пользователь Сообщений: 5 |
#1 25.06.2015 22:09:19 Доброго времени суток!
Изменено: Lolik — 25.06.2015 22:18:18 |
||
Пытливый Пользователь Сообщений: 4587 |
Эм… ну у вас переменная не объявлена. Массив br без размерности. Кому решение нужно — тот пример и рисует. |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
#3 25.06.2015 22:41:06 Что-то я сомневаюсь, что именно в таком виде работает…Либо этот код завязан на другие, либо где-то еще объявлена переменная br как массив:
Без этого код просто по определению не может работать. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
#4 25.06.2015 22:43:08
Тоже подозреваю, что в одном из модулей объявлена, как глобальная. |
||
Lolik Пользователь Сообщений: 5 |
#5 25.06.2015 22:47:12 Да объявлена как глобальная
|
||
Lolik Пользователь Сообщений: 5 |
#6 25.06.2015 22:49:44 Порядок тоже определен
|
||
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
Слушайте, думаете мы тут сможем по двум совершенно разным кускам кода понять и дать ответ? В коде выше не видно ни объявления, ни что там дальше происходит. Я не хочу сидеть и гадать. Либо файл выкладывайте, либо вряд ли вообще получите ответ. Возможные причины я описал выше — сидите, ковыряйтесь… Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Hugo Пользователь Сообщений: 23251 |
Подозреваю что виновато Option Base |
The_Prist Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
Тоже была такая мысль. Но гадать можно сколько угодно. Явно при миграции с одного ПК на другой что-то потерялось. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Hamit Пользователь Сообщений: 1 |
#10 13.03.2020 16:05:09 Слегка похожая проблема вот код:
на второй итерации цикла For Each выходит ошибка: Subscript out of range ругается на строку:
при этом, если k заменить на число, к примеру 300 (заведомо выше, чем требуется), то все работает норм
так то вроде «костыль» работает, но хотелось бы понять, почему переопределение массива через переменную не дает результата? Изменено: Hamit — 13.03.2020 16:08:31 |
||||||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14182 Профессиональная разработка приложений для MS Office |
#11 13.03.2020 16:25:43
ReDim Preserve может изменять только одну размерность, и только последнюю. Т.е. можно только так:
а еще правильнее сначала определить размер для массива(Ваш код это позволяет):
P.S.
а я еще 5 лет назад не увидел толком вопроса к форуму, а не к гадалкам Изменено: Дмитрий(The_Prist) Щербаков — 13.03.2020 16:26:44 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||||||