Expected array ошибка vba excel

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»

Roman777

Дата: Понедельник, 13.04.2015, 17:21 |
Сообщение № 1

Группа: Проверенные

Ранг: Ветеран

Сообщений: 980


Репутация:

127

±

Замечаний:
0% ±


Excel 2007, Excel 2013

Добрый день!
Вроде всё просто, где-то, наверное, небольшая ошибка. Но никак не могу понять что не так:
Говорит «compile error: expected array» на строку
[vba][/vba]
в следующем макросе:
[vba]

Код

Sub Вставка_Фото_с_первого_листа_в_файл()
Dim i As Long, i1 As Long
Dim sht As Worksheet
Dim NameRazdel As String
Dim Stolbec As Integer, Stolbec2 As Integer
Dim Articuls As String, Fotos As String
Dim kol As Long

NameRazdel = InputBox(«Введите наименование раздела», «Наименование раздела», «Розетки и выключатели.»)
Stolbec = InputBox(«Введите номер столбца, в котором необходимо добавить данные», «Столбец редактирования данных», «8»)
Stolbec2 = InputBox(«Введите номер столбца на 1м листе, откуда извлекаем данные», «Столбец извлекаемых данных», «10»)
Time_1 = Timer
i1_n = Worksheets(1).Cells(Rows.Count, 3).End(xlUp).Row
ReDim Articuls(i1_n)
ReDim Fotos(i1_n)
For i1 = 1 To i1_n
Articuls(i1) = Worksheets(1).Cells(i1, 3)
Fotos(i1) = Worksheets(1).Cells(i1, Stolbec2)
Next i1
For Each sht In ActiveWorkbook.Worksheets
If sht.Cells(1, 1) = NameRazdel Then
Application.ScreenUpdating = False
i_n = sht.Cells(Rows.Count, 3).End(xlUp).Row
   For i = 3 To i_n
      If sht.Cells(i, Stolbec) = «» Then
         For i1 = 1 To i1_n
            If sht.Cells(i, 3) = Articuls(i1) Then
               sht.Cells(i, Stolbec) = Fotos(i1)
               kol = kol + 1
            End If
         Next i1
      End If
   Next i
End If
Next sht
Application.ScreenUpdating = True
time_ = Time_1 — Timer
Time_delta = Format(time_ / 24 / 60 / 60, «hhч mmм ssс»)
MsgBox («Выполнено за » & Time_delta & Chr(13) & «Количество добавленных фотографий :» & kol)
End Sub

[/vba]


Много чего не знаю!!!!

 

Ответить

Rioran

Дата: Понедельник, 13.04.2015, 17:26 |
Сообщение № 2

Группа: Авторы

Ранг: Ветеран

Сообщений: 903


Репутация:

290

±

Замечаний:
0% ±


Excel 2013

Roman777, здравствуйте.

У Вас переменная объявлена как обычная строка:

[vba]

Код

Dim Articuls As String

[/vba]
Можете добавить скобок:

[vba]

Код

Dim Articuls() As String

[/vba]


Роман, Москва, voronov_rv@mail.ru
Яндекс-Деньги: 41001312674279

 

Ответить

Roman777

Дата: Понедельник, 13.04.2015, 17:28 |
Сообщение № 3

Группа: Проверенные

Ранг: Ветеран

Сообщений: 980


Репутация:

127

±

Замечаний:
0% ±


Excel 2007, Excel 2013

Rioran, hands спасибо большое, что-то я в упор не видел этого)))


Много чего не знаю!!!!

 

Ответить

Kuzmich

Дата: Понедельник, 13.04.2015, 17:34 |
Сообщение № 4

Группа: Проверенные

Ранг: Ветеран

Сообщений: 707


Репутация:

154

±

Замечаний:
0% ±


Excel 2003

Цитата

Dim Articuls As String, Fotos As String

Объявляйте как массив

 

Ответить

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:

Compile error: Expected array

The code is written to loop through the following rows in Excel:

Sample Excel file with a bunch of address data

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

#1

01.08.2013 12:04:24

Добрый день коллеги!
Ситуация делаю UserForm где есть выпадающий список с названиями
использую combobox
в него мне нужно добавить список из листа

Написал вот такой код…..
Выдает ошибку Compile error: Expected array
и выделяет Redim preserve rngY(1
если rngY меняю на Вариант
то выделяет ее же и пишет Type mismatch
В общем не могу понять что не так делаю

Код
Private Sub DolgnosList_DropButtonClick()
Dim colDolgnost As New Collection
Dim i%, k%
Dim rngY As String
Dim intROW As Integer

intROW = Worksheets("Должность".Cells(Rows.Count, 1).End(xlUp).Row
Do
i = i + 1
ReDim Preserve rngY(1 To intROW - 1)
rngY(i) = Worksheets("Должность".Cells(i + 1, 1)
Loop Until rngY(i) = intROW - 1

For k = 1 To i - 1
DolgnosList.AddItem rngY(k)
Next k
End Sub
 

Юрий М

Модератор

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

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

А зачем вообще ReDim Preserve? Забирайте в массив и сразу этот массив в ComboBox. Ну или циклом AddItem.

 

KuklP

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

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

E-mail и реквизиты в профиле.

#3

01.08.2013 12:33:20

Цитата
Niarah пишет: что не так делаю

Многое!  :)

Цитата
Юрий М пишет: А зачем вообще ReDim Preserve?

Да еще в цикле. Размерность же не меняется.
Вместо всего того великолепия, одна строчка кода:

Код
Private Sub DolgnosList_DropButtonClick()
    DolgnosList.List = Range("a1:a" & Cells(Rows.Count, 1).End(xlUp).Row).Value
End Sub

И используйте теги для оформления кода.

Изменено: KuklP19.10.2015 16:13:26

Я сам — дурнее всякого примера! …

 

Niarah

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

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

#4

01.08.2013 12:37:47

Цитата
Юрий М пишет:
А зачем вообще ReDim Preserve? Забирайте в массив и сразу этот массив в ComboBox. Ну или циклом AddItem.

М-м-м в первом варианте я задаю rngY как массив ? array ? или new collection
я еще слаб в массивах )

а циклом вот так ?

Код
for i = 1 to introw ' introw = число строк в списке
   dolgnosList.additem worksheets("Должность".cells(i,1)
next i

А потом то что они выберут мне нужно внести в лист
.cells(1,1)=dolgnosList.selected
вот так ?

 

Юрий М

Модератор

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

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

 

Niarah

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

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

 

Sanya_Bars

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

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

Спасибо мало…..
Человек вопрос задал а вы ему так и не ответили а предложили свое решение
Ваш форум читает не только создатель темы но еще многие пользователи интернета по запросу в поисковике
а данное решение мне вот например не подходит
Мне нужно знать где я ошибся чтоб больше не повторять эти ошибки
Так что буду искать дальше в чем я ошибся

 

Юрий М

Модератор

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

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

Почему предложенное решение не подходит? И какая проблема у Вас — как проявляется ошибка?

 

Sanya_Bars

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

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

1.Я свою проблему решил
при создании массива ReDim newarr(…бла бла бла) VBA ругался  .Compile error: Expected array
я ошибочно присвоил переменную as Range для массива newarr
замена переменнной на variant помогла… ну либо просто без объявления
2. мне в коде не нужен UserForm и выпадающий список, а нужен был именно массив для работы с данными, я просто скопировал его
из своего другого кода но там он работал а в новом нет. долго ломал голову. в старом коде Dim далеко в верху

я сам не программист и VBA недели 2 изучаю, так что много детских ошибок ни одного действия без интернета не получилось бы
щас появилось время и я пытаюсь облегчить себе жизнь при помощи VBA
очень часто ошибаюсь с синтаксисом

По поводу темы форума, меняем на variant  массив и дальше начинает ругаться VBA «…пишет Type mismatch…»
дальше надо смотреть где собака порылась [IMG]
……посмотрел….поправте если я не прав чтоб применить ReDim Preserve rngY() нужно сначала создать ReDim rngY()

Niarah

у Вас что-то в цикле напутано, у Вас условие выхода из цикла сравнение значения массива и номера предпоследней строки
такое совпадение редко может у Вас в ячейках буквы вообще
может rngY(i) = intROW — 1 заменить на  i = intROW — 1 или rngY(i) = rngY(intROW — 1)
мне не понятна задача что вы хотите сделать с данными
может нужно просто попробовать другой ЦИКЛ

 

Софья Золкина

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

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

#10

19.10.2015 16:06:26

Sanya_Bars, Спасибо тебе добрый человек. Я долго мучилась с этим «Type mismatch…».
мой исходник выглядел так:

Скрытый текст

После я решила применить ваше указание по поводу «сначала создать ReDim «, но подумав, получается без Preserve мой массив не сохраняет предыдущие вычисления с снова переопределяет массив. Немного подумав я решила обмануть программу и написала так. и все заработало:

Скрытый текст

Удачи всем. Возможно мой опыт тоже кому-то поможет, как мне помог опыт Sanya_Bars.

Изменено: Софья Золкина19.10.2015 16:13:02

Понравилась статья? Поделить с друзьями:
  • Exit status 1 ошибка компиляции для платы arduino leonardo
  • Exit code 1 код ошибки
  • Exist ошибка при выполнении запроса post к ресурсу
  • Exhaust system warning на daf ошибка
  • Exel ошибка при направлении команды приложению