Vba excel redim preserve subscript out of range

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). В чём причина?

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Sub z11()
 
Dim f(), alf, sl As String
Dim i, l As Integer
 
alf = "адлпшгезывжэътьвб" 'новый алфавит
sl = Cells(45, 1).Text 'слово извлекаем из ячейки А45
 
l = Len(sl) 'находим длину слова
 
For i = 1 To l 'присваиваем буквам слова новые значения алф.
f(i) = Mid(alf, i, 1)
 Next i
 
Cells(45, 2) = Join(f(i), "") ' соединяем массив букв в единое новое слово.
End Sub



0



Lubocka

15.11.2011, 19:52

2

Если Вы хотите применять динамический массив, почитайте это:

Dim MyArray () AS Integer
В этом примере объявляется так называемый динамический массив, в отличие от рассматривавшихся выше статических массивов. Количество элементов массива может быть неизвестным вплоть до его первого применения. Перед первым применением динамического массива необходимо явно указать количество составляющих его элементов, иначе вы получите сообщение об ошибке, и программа работать не будет. Для того чтобы задать размер массива используется оператор ReDim, имеющий следующий синтаксис:

ReDim [Preserve] ИмяМассива(НомерПоследнегоЭлемента)

Оператор ReDim можно применять многократно к одному и тому же динамическому массиву. По умолчанию после каждого применения этого оператора хранившиеся в массиве данные пропадают, поскольку массив переинициализируется. Избежать этого можно, применив в операторе ReDim необязательное ключевое слово Preserve. В этом случае массив не будет повторно инициализироваться. Естественно, ключевое слово Preserve имеет смысл применять к имени динамического массива, только начиная со второго применения оператора ReDim. Кроме того, на применение этого ключевого слова накладывается еще несколько ограничений.
• Нельзя применять ключевое слово Preserve при изменении размерности динамического массива.
• • Применять ключевое слово Preserve в многомерных массивах можно только к его последней размерности. Например, после применения оператора ReDim MyArray( 10,15) допустим оператор ReDim*Preserve MyArray(10,20). С другой стороны, применение оператора ReDim Preserve MyArray(15,20) недопустимо.
При уменьшении размера динамического массива значения элементов, на которые массив уменьшается, соответственно теряются. При увеличении размера массива все его новые элементы будут инициализированы исходя из типа массива. То есть новые элементы числового массива будут заполнены нулями, массива типа String — пустыми строками, и т.д.

0 / 0 / 0

Регистрация: 18.10.2011

Сообщений: 5

15.11.2011, 20:10

 [ТС]

3

Благодарю, разобралась.
:cool:



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

15.11.2011, 20:10

Помогаю со студенческими работами здесь

‘Runtime error ‘9’: Subscript out of range’
Приветствую.
Это шаблон EXCEL, для вставки фото, на второй строчке выходит ошибка ‘Runtime error…

Word: Error — Subscript Out of Range
ReDim mas(1 To kd, 1 To 1)

ReDim Preserve mas(kd, 1 To UBound(mas, 2) + 1)Ругается на эту…

Error 9: Subscript out of range — VBA
Выходит ошибка, не знаю в чём проблема?

Sub задача()
Dim h0 As Single, h11 As Single, h12…

Run-time error ‘9’: Subscript out of range
Программа успешно работает в Office 2007 в WinXP, Win7, а вот в Windows 8 после заполнения формы…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

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

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

VBA Subscript Out of Range

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

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.

VBA Subcript Out of Range Example 1

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

Code:

Sub Macro2()

   Sheets("Sales").Select

End Sub

VBA Subcript Out of Range Example 1-1

If we run this code using the F5 key or manually, we will get the Run-time error ‘9’: “Subscript out of range.”

VBA Subcript Out of Range Example 1-2

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

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

VBA Subcript Out of Range Example 1-4

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

VBA Subcript Out of Range Example 2

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

Range Example 2-1

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

Range Example 2-2

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

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

Subcript Out of Range Example 3-1

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
Регистрация: 12.01.2015

#1

25.06.2015 22:09:19

Доброго времени суток!
Имеется программа в Excel c макросами на VBA, состоит из нескольких модулей, процедур типа Sub. Проблема в том, что на некоторых компах запускаются нормально, а на моем не в какую выкидывает ошибку «run time error 9 subscript out of range» причем не запускается ни одна из всех процедур… Посмотрел много инфы про это, но все же разобраться не могу. В общем в коде не предусмотрено подгружать данные из других файлов, все выполняется на одном листе. Может библиотеки какие не подгруженны? или настройки Excel или Windows?
Пример прилагаю

Код
Sub Gn()
br(0) = 0: br(7) = 0  '!!!!Тут сразу ошибка!!!
br(1) = 20: br(2) = 0.234: br(3) = 20: br(4) = 40: br(5) = 0.468: br(6) = 40
tr(1) = 0.1: tr(2) = 20: tr(3) = 0.1: tr(4) = 0.1: tr(5) = 20: tr(6) = 0.1
End Sub

Изменено: Lolik25.06.2015 22:18:18

 

Пытливый

Пользователь

Сообщений: 4587
Регистрация: 22.12.2012

Эм… ну у вас переменная не объявлена. Массив br без размерности.
Ну так, навскидку.

Кому решение нужно — тот пример и рисует.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#3

25.06.2015 22:41:06

Что-то я сомневаюсь, что именно в таком виде работает…Либо этот код завязан на другие, либо где-то еще объявлена переменная br как массив:

Код
Dim br(0 to n) 'n - некое число
'или
Dim br()
'а далее в модулях нечто вроде
Redim br(1 to n)
'или
Redem Preserve br(n)

Без этого код просто по определению не может работать.
А Ваша ошибка может быть вызвана тем, что не все модули скопированы или порядок вызова процедур неверен. В таком случае ни объявления, ни назначения массиву размерности не происходит. Отсюда и ошибка — попытка обратиться к несуществующему элементу массива.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#4

25.06.2015 22:43:08

Цитата
The_Prist написал:
либо где-то еще объявлена переменная br как массив:

Тоже подозреваю, что в одном из модулей объявлена, как глобальная.

 

Lolik

Пользователь

Сообщений: 5
Регистрация: 12.01.2015

#5

25.06.2015 22:47:12

Да объявлена как глобальная
То что выше это блок ввода параметров

Код
Sub Stergen() 'la,et,ee,k0,k1,pi,ro,KN,KM,cN,cM
Dim v#
la = 250: et = 0.001619: ee = 0.8: k0 = 0: k1 = 0: pi = 4 * Atn(1)
'KN = 1 / 2: KM = Sqr(3): sma = 1
Gn
KNKMsma
     ro = KM / la: cN = KN * et * la ^ 2: cM = cN * ro
End Sub
 

Lolik

Пользователь

Сообщений: 5
Регистрация: 12.01.2015

#6

25.06.2015 22:49:44

Порядок тоже определен

Код
Sub Osnovnaja() 'bb,gg,qq
Stergen
Nachform
Nachvivod
Schet
End Sub
 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Слушайте, думаете мы тут сможем по двум совершенно разным кускам кода понять и дать ответ? В коде выше не видно ни объявления, ни что там дальше происходит. Я не хочу сидеть и гадать. Либо файл выкладывайте, либо вряд ли вообще получите ответ. Возможные причины я описал выше — сидите, ковыряйтесь…

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

Подозреваю что виновато Option Base

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Тоже была такая мысль. Но гадать можно сколько угодно. Явно при миграции с одного ПК на другой что-то потерялось.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Hamit

Пользователь

Сообщений: 1
Регистрация: 13.03.2020

#10

13.03.2020 16:05:09

Слегка похожая проблема
ответа в данной ветке так толком и не увидел

вот код:

Код
Sub FreeIpAddress()
 Dim IpAddressArray(), NetworkArray() As Variant
 Dim Cell As Range
 Dim k As Integer
 Dim v As Variant
 'cells to array v1
 IpAddressArray = Sheets("PublicIntList").Range("B2:B" & Sheets("PublicIntList").Cells(Sheets("PublicIntList").Rows.Count, "B").End(xlUp).Row).Value
 'cells to array v2 notEmpty
 k = 1
 'ReDim Preserve NetworkArray(300, 1)
 For Each Cell In Sheets("PublicIntList").Range("C:C").SpecialCells(xlCellTypeConstants)
  ReDim Preserve NetworkArray(k, 1)
  NetworkArray(k, 1) = Cell.Value
  'NetworkArray(k, 2) = Cell.Address
  k = k + 1
 Next
End Sub

на второй итерации цикла For Each выходит ошибка:

Subscript out of range

ругается на строку:

Код
ReDim Preserve NetworkArray(k, 1)

при этом, если k заменить на число, к примеру 300 (заведомо выше, чем требуется), то все работает норм

Код
ReDim Preserve NetworkArray(300, 1)

так то вроде «костыль» работает, но хотелось бы понять, почему переопределение массива через переменную не дает результата?
заранее спасибо

Изменено: Hamit13.03.2020 16:08:31

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#11

13.03.2020 16:25:43

Цитата
Hamit написал:
ругается на строку

ReDim Preserve может изменять только одну размерность, и только последнюю. Т.е. можно только так:

Код
ReDim Preserve NetworkArray(1, k)

а еще правильнее сначала определить размер для массива(Ваш код это позволяет):

Код
Dim rr as range,rc as range
on error resume next
set rr = Sheets("PublicIntList").Range("C:C").SpecialCells(xlCellTypeConstants)
on error goto 0
If not rr is nothint then
ReDim Preserve NetworkArray(1 to rr.Cells.count, 1 to  2)
k = 1
For Each rc In rr.cells
  NetworkArray(k, 1) = Cell.Value
  NetworkArray(k, 2) = Cell.Address
  k = k + 1
 Next
end if

P.S.

Цитата
Hamit написал:
ответа в данной ветке так толком и не увидел

а я еще 5 лет назад не увидел толком вопроса к форуму, а не к гадалкам :)

Изменено: Дмитрий(The_Prist) Щербаков13.03.2020 16:26:44

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

Понравилась статья? Поделить с друзьями:
  • Vba excel recordset свойства
  • Vba excel sheets by name
  • Vba excel range пример
  • Vba excel range по номерам ячеек
  • Vba excel range количество строк