Can anyone help me?
I have been getting a compile error (…: «Expected Array») when dealing with arrays in my Excel workbook.
Basically, I have one ‘mother’ array (2D, Variant type) and four ‘baby’ arrays (1D, Double type). The called subroutine creates the publicly declared arrays which my main macro ends up using for display purposes. Unfortunately, the final of the baby arrays craps out (giving the «Compile Error: Expected Array»). Strangely, if I remove this final baby array (‘final’ — as in the order of declaration/definition) the 2nd to last baby array starts crapping out.
Here is my code:
Public Mother_Array() as Variant, BabyOne_Array(), BabyTwo_Array(), BabyThree_Array(), BabyFour_Array() as Double 'declare may other variables and arrays, too
Sub MainMacro()
'do stuff
Call SunRaySubRoutine(x, y)
'do stuff
Range("blah") = BabyOne_Array: Range("blahblah") = BabyTwo_Array
Range("blahbloh" = BabyThree_Array: Range("blahblue") = BabyFour_Array
End Sub
Sub SunRaySubRoutine(x,y)
n = x * Sheets("ABC").Range("A1").Value + 1
ReDim Mother_Array(18, n) as Variant, BabyOne_Array(n), BabyTwo_Array(n) as Double
ReDim BabyThree_Array(n), BabyFour_Array(n) as Double
'do stuff
For i = 0 to n
BabyOne_Array(i) = Mother_Array(0,i)
BabyTwo_Array(i) = Mother_Array(2,i)
BabyThree_Array(i) = Mother_Array(4,i)
BabyFour_Array(i) = Mother_Array(6,i)
Next
End Sub
I have tried to declare all arrays as the Variant type, but to no avail. I have tried to give BabyFour_Array() a different name, but to no avail.
What’s really strange is that even if I comment out the part which makes the BabyFour_Array(), the array still has zero values for each element.
What’s also a bit strange is that the first baby array never craps out (although, the 2nd one crapped out once (one time out of maybe 30).
BANDAID: As a temporary fix, I just publicly declared a fifth dummy array (which doesn’t get filled or Re-Dimensioned). This fifth array has no actual use besides tricking the system out of having the «Compile Error: Expected Array».
Does anyone know what’s causing this «Compile Error: Expected Array» problem with Excel VBA?
Thanks,
Elias
Не хочет записывать массив «Expected array» |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
An array is a type of variable which differs from a ‘normal’ variable in that it can hold multiple values rather than just one value at a time. There can be a few reasons why you would receive an “Expected array” error.
Let’s look at some code that we have to loop through a range of cells on an Excel worksheet.
Option Explicit Public n As Long, i As Long, Status As String Private Sub GetStatus() 'count the rows in the list of clients n = ClientList.Range("G5", ClientList.Range("G5").End(xlDown)).Rows.Count 'redim the Status to have the amount of rows we have counted in the 'array ReDim Status(n) 'loop through the array and get the status of the account For i = 1 To n If ClientList.Range("G5").Offset(i, 0) < 0 Then Status(i) = "Debit" Else Status(i) = "Credit" End If Next i End Sub
The code above looks perfect, but when we run it – this error will occur:
The code is written to loop through the following rows in Excel:
The first line of the code will count how many rows are in the list, and then it will ReDim the Status variable to be able to contain that amount of rows. The Status variable has been declared to hold multiple values – and the code will loop through the cells from G5 to the last cell, and store either Debit or Credit as the status for that cell, depending on what is in the appropriate cell.
At a glance, the code looks fine, but there clearly is a problem as we get a compile error. This type of error can be hard to find.
If we look closely at the code, and at the error – the error says ‘expected array’ – and we have re-dimmed the variable Status in line 2 of the code. However, in order to ReDim an Array, we first have to actually declare an Array – and there lies our problem. We have declared the Status variable as a String – but we have NOT declared it as a String ARRAY. The solution is annoyingly simple – which is why so many people make the same error. The correct code is below – can you spot the amendment?
Option Explicit Public n As Long, i As Long, Status() As String Private Sub GetStatus() 'count the rows in the list of clients n = ClientList.Range("G5", ClientList.Range("G5").End(xlDown)).Rows.Count 'redim the Status to have the amount of rows we have counted in the 'array ReDim Status(n) 'loop through the array and get the status of the account For i = 1 To n If ClientList.Range("G5").Offset(i, 0) < 0 Then Status(i) = "Debit" Else Status(i) = "Credit" End If Next i End Sub
Look at the Public variables at the top of the module – just under Option Explicit.
In the first code snippet – the variables look like this:
Public n As Long, i As Long, Status As String
But in the second code snipped, the variables now look like this:
Public n As Long, i As Long, Status() As String
The Status has now been declared as an ARRAY – simply by adding the brackets behind the word STATUS. This now enables the variable Status to hold multiple values, and not just one value.
So in summary, if you get this message, there is a variable in your code that is being expecting to be populated with multiple values, but your declaration of the variable is indicating that only a single value can go into that variable. You need to check the syntax of your code carefully – it may be that you have an error in your code and you DON’T actually want an array, or you may have declared the variable incorrectly.
See also: Can’t Assign to Array
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Expected array |
vblr6.chm1011151 |
vblr6.chm1011151 |
office |
9b38809b-2fc1-8bcf-f13e-05570fd1673c |
06/08/2017 |
medium |
A variable name with a subscript indicates the variable is an array. This error has the following cause and solution:
-
The syntax you specified is appropriate for an array, but no array with this name is in scope.
Check to make sure the name of the variable is spelled correctly. Unless the module contains Option Explicit, a variable is created on first use. If you misspell the name of an array variable, the variable may be created, but not as an array.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
Niarah Пользователь Сообщений: 34 |
#1 01.08.2013 12:04:24 Добрый день коллеги! Написал вот такой код…..
|
||
Юрий М Модератор Сообщений: 60770 Контакты см. в профиле |
А зачем вообще ReDim Preserve? Забирайте в массив и сразу этот массив в ComboBox. Ну или циклом AddItem. |
KuklP Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
#3 01.08.2013 12:33:20
Многое!
Да еще в цикле. Размерность же не меняется.
И используйте теги для оформления кода. Изменено: KuklP — 19.10.2015 16:13:26 Я сам — дурнее всякого примера! … |
||||||
Niarah Пользователь Сообщений: 34 |
#4 01.08.2013 12:37:47
М-м-м в первом варианте я задаю rngY как массив ? array ? или new collection а циклом вот так ?
А потом то что они выберут мне нужно внести в лист |
||||
Юрий М Модератор Сообщений: 60770 Контакты см. в профиле |
|
Niarah Пользователь Сообщений: 34 |
|
Sanya_Bars Пользователь Сообщений: 2 |
Спасибо мало….. |
Юрий М Модератор Сообщений: 60770 Контакты см. в профиле |
Почему предложенное решение не подходит? И какая проблема у Вас — как проявляется ошибка? |
Sanya_Bars Пользователь Сообщений: 2 |
1.Я свою проблему решил я сам не программист и VBA недели 2 изучаю, так что много детских ошибок ни одного действия без интернета не получилось бы По поводу темы форума, меняем на variant массив и дальше начинает ругаться VBA «…пишет Type mismatch…» Niarah у Вас что-то в цикле напутано, у Вас условие выхода из цикла сравнение значения массива и номера предпоследней строки |
Софья Золкина Пользователь Сообщений: 14 |
#10 19.10.2015 16:06:26 Sanya_Bars, Спасибо тебе добрый человек. Я долго мучилась с этим «Type mismatch…».
После я решила применить ваше указание по поводу «сначала создать ReDim «, но подумав, получается без Preserve мой массив не сохраняет предыдущие вычисления с снова переопределяет массив. Немного подумав я решила обмануть программу и написала так. и все заработало:
Удачи всем. Возможно мой опыт тоже кому-то поможет, как мне помог опыт Sanya_Bars. Изменено: Софья Золкина — 19.10.2015 16:13:02 |
||