Can t assign to array vba excel

An array is nothing but a collection of elements of the same data type. Arrays keep your data organized for easy usage and maintenance. In VBA, Arrays can either be static or dynamic. Static arrays have a pre-determined size and number of elements — and they are not re-sizable. On the other hand, dynamic arrays offer re-sizing depending on need.

First, a couple sample arrays…

To understand how to fix this error, you need to first understand the basics of how to use arrays in VBA.

Here are some code snippets that demonstrate how to declare, initialize and use simple arrays.

  • An array to hold a list of car brands
Sub array_cars()

'declaring variable
Dim arr_cars() As Variant

'define the size of the array
ReDim arr_cars(5)

'initialize array elements
 arr_cars(0) = "Benz"
 arr_cars(1) = "Maruthi"
 arr_cars(2) = "Hyundai"
 arr_cars(3) = "Ford"
 arr_cars(4) = "Nissan"

'print all elements
For i = LBound(arr_cars) To UBound(arr_cars)
    Debug.Print arr_cars(i)
Next

End Sub
  • An array to hold the details student records and their total grades in a 2-dimensional array.
Sub array_2d_demo()

'declaring and defining size of an array
'3 means 4 rows starting from 0 to 3 and 1 means 2 columns starting from 0 to 1
Dim arr_stu(3, 1) As Variant

'initialize array elements
 arr_stu(0, 0) = "Jackson"
 arr_stu(0, 1) = 89
 arr_stu(1, 0) = "Vincent"
 arr_stu(1, 1) = 57
 arr_stu(2, 0) = "Sathyan"
 arr_stu(2, 1) = 90
 arr_stu(3, 0) = "Viji"
 arr_stu(3, 1) = 67
 
'print all elements
For i = LBound(arr_stu) To UBound(arr_stu)
    
    Debug.Print "Student Name : " & arr_stu(i, 0)
    Debug.Print "Marks : " & arr_stu(i, 1)
    Debug.Print "End of record"
Next

End Sub

Output :

Student Name : Jackson

Marks : 89

End of record

Student Name : Vincent

Marks : 57

End of record

Student Name : Sathyan

Marks : 90

End of record

Student Name : Viji

Marks : 67

End of record

Compile error: “Can’t assign to array” causes

Compile error: Can't assign to array

This is a compile time error that occurs when you try to assign improper or irrelevant data to an array. Below are some reasons that can cause this error. We’ll have a look at these causes and their corresponding solutions one-by-one.

Assigning a string to an array or an element of an array

Suppose we have an array defined and we want to initialize the array with data, then we should follow either of these methods:

  1. We should assign values to each element of an array separately or one-by-one using the array’s indexes
  2. Assigning one array to another array can be done if the array to which data has to be assigned is a dynamic resizable array and the two arrays are the same datatype.

If the above rules are not followed then the compile time error  “Can’t assign to array” will occur.

Let’s take a look at a couple examples to understand better.

Sub array_assign()

'declaring variable
Dim arr_cars1() As Variant

'initialize array elements for one array. Invalid assignment
arr_cars1() = "abcd"

End Sub

In this example  the line arr_cars1() = "abcd" does not specify to which element of the array , we need to assign the string value “abcd”. Hence it generates the compile error “Can’t assign to array.”

Element not specified and error occurs

To address this, in the code below we define the size of the array and assign the value to any one element of the array.

Sub array_assign()

'declaring variable
Dim arr_cars1() As Variant

'define the size of the array
ReDim arr_cars1(3)

'initialize array elements for one array. Invalid assignment
arr_cars1(0) = "abcd"

End Sub

Assigning a value of different datatype to an element of an array

In the following example, we try to assign that values of a string array to an integer array. This again leads to the compile error “Can’t assign to array.”

Sub array_assign()

'declaring variable
Dim arr_cars1() As String
Dim arr_cars2() As Integer

ReDim arr_cars1(5)

'initialize array elements for one array
 arr_cars1(0) = "Benz"
 arr_cars1(1) = "Maruthi"
 arr_cars1(2) = "Hyundai"
 arr_cars1(3) = "Ford"
 arr_cars1(4) = "Nissan"

arr_cars2() = arr_cars1()

'print all elements of first array
For i = LBound(arr_cars1) To UBound(arr_cars1)
    Debug.Print arr_cars1(i)
Next

'print all elements  of second array
For i = LBound(arr_cars2) To UBound(arr_cars2)
    Debug.Print arr_cars2(i)
Next

End Sub

datatypes are mismatched

This can be solved if the datatype of the array arr_cars2() is set to the same datatype as arr_cars1().

Note: This compile error will occur even if the array on the left side of the assignment is of the variant datatype.

Correct output with list of cars

Split a string to an array with a pre-defined size

The result of a split function is an array. This result cannot be assigned to an array for which size is already set. Doing so will cause — you guessed it — the compile error “Can’t assign to array.”

Sub split_array()

    'declare an array and define it's size
    Dim arr_days(7) As Variant
    
    'initialize the value of string
    strdays = "sunday,monday,tuesday,wednesday,thursday,friday,saturday"
    
    'split and assign to an array
    arr_days = Split(strdays, ",")
    
End Sub

The solution is that the array should not have a pre-defined size as I demonstrate in the example below.

Sub split_array()

    'declare an array and define it's size
    Dim arr_days As Variant
    
    'initialize the value of string
    strdays = "sunday,monday,tuesday,wednesday,thursday,friday,saturday"
    
    'split and assign to an array
    arr_days = Split(strdays, ",")
    
    'try printing all values
    For i = LBound(arr_days) To UBound(arr_days)
        Debug.Print arr_days(i)
    Next
    
End Sub

Output:

sunday

monday

tuesday

wednesday

thursday

friday

saturday

Below is another example where we try to assign the return value of a split function to a string array whose size is pre-defined.

Sub split_array()

    'declare an array and define it's size
    Dim arr_num(3) As String
    
    'initialize the value of string
    strdays = "1,2,3"
    
    'split and assign to an array
    arr_num() = Split(strdays, ",")
    
    'try printing all values
    For i = LBound(arr_num) To UBound(arr_num)
        Debug.Print arr_num(i)
    Next
    
End Sub

In the code snippet, removing that “3” in the dim statement can resolve this compile error.

Compile error: Can't assign to array -- occurs because array size is set to 3

Conclusion

The compile error “Can’t assign to array” can be easily resolved or avoided by properly following the rules for assignment of values to an array.

To solve this problem, you have to consider:

  1. What the datatype should be for the array on the left side of the assignment statement
  2. What should be the size of the array
  3. Can the size be pre-defined or not

Remember, the datatype of the two arrays should be of the same datatype for assignment to happen successfully.

I’m trying implement the next code and get the error —

cant assign to array

Where is the error ? Note that if i type Dim arrf() As Variant instead of Dim arrf(5) As Variant I get error —

type mismatch

Public Function calc(ByVal value As Integer, ByVal num As Integer) As Variant()

Dim arr(5) As Variant
Dim x As Double

If value >= num Then
    x = value - Application.RoundDown(value / num, 0) * num
    arr(0) = x
    arr(1) = num - arr(0)
    arr(2) = Application.RoundUp(value / num, 0)
    arr(3) = 1
    arr(4) = Application.RoundDown(value / num, 0)
    arr(5) = 1
Else
    x = num - Application.RoundDown(num / value, 0) * value
    arr(0) = x
    arr(1) = value - arr(0)
    arr(2) = Application.RoundUp(num / value, 0)
    arr(3) = 1
    arr(4) = Application.RoundDown(num / value, 0)
    arr(5) = 1
    calc = arr
End If

End Function


Sub cellsfunc()

With Application
    .DisplayAlerts = False
    .EnableEvents = False
    .ScreenUpdating = False
End With

Dim lastrow As Integer
Dim counter As Integer

Dim arrf(5) As Variant

lastrow = Cells(Rows.Count, 2).End(xlUp).Row
For counter = 2 To lastrow Step 2
    arrf = calc(Cells(4, counter), Cells(4, counter + 1))
Next counter

With Application
    .DisplayAlerts = True
    .EnableEvents = True
    .ScreenUpdating = True
End With

End Sub

thanks ahead to all helpers

Shai Rado's user avatar

Shai Rado

32.9k6 gold badges26 silver badges51 bronze badges

asked Sep 18, 2016 at 12:55

shay's user avatar

2

You have arrf declared as a fixed size array:

Dim arrf(5) As Variant

An array returning function can’t return a fixed size array — only a dynamic one. You just need to declare it as a dynamic array:

Dim arrf() As Variant

answered Sep 18, 2016 at 13:58

Comintern's user avatar

CominternComintern

21.7k5 gold badges33 silver badges80 bronze badges

There’s an issue in your function calc() : it only returns a value when it goes through the else, and not the if

It should probably be this:

Public Function calc(ByVal value As Integer, ByVal num As Integer) As Variant()

  Dim arr(5) As Variant
  Dim x As Double
  If value >= num Then
    x = value - Application.RoundDown(value / num, 0) * num
    arr(0) = x
    arr(1) = num - arr(0)
    arr(2) = Application.RoundUp(value / num, 0)
    arr(3) = 1
    arr(4) = Application.RoundDown(value / num, 0)
    arr(5) = 1
  Else
     x = num - Application.RoundDown(num / value, 0) * value
    arr(0) = x
    arr(1) = value - arr(0)
    arr(2) = Application.RoundUp(num / value, 0)
    arr(3) = 1
    arr(4) = Application.RoundDown(num / value, 0)
    arr(5) = 1
  End If
  calc = arr ' <------- THIS
End Function

answered Sep 18, 2016 at 13:30

Thomas G's user avatar

Thomas GThomas G

9,7167 gold badges29 silver badges40 bronze badges

If you use a typed array in VBA script always use ReDim.. size initialization. You may use a typed array in a dictionary value or everywhere like a regular variable.

Public Function readData(ws As Worksheet, arr As Scripting.Dictionary) As Boolean
  Dim iRow as long 
  Dim key as String 
  Dim sVal() As String
  ReDim sVal(0 to 1) as String 

  For iRow=2 to 1000
    key = ws.cells(iRow,1)
    sVal(0) = ws.Cells(iRow, 5)
    sVal(1) = ws.Cells(iRow, 6)
    call arr.Add(key, sVal)
  Next
  readData=true 
End Function

Public Function writeData(ws As Worksheet, arr As Scripting.Dictionary) As Long
  Dim iRow as long 
  Dim key as String 
  Dim sVal() As String
  ReDim sVal(0 to 1) as String 

  For iRow=2 to 1000
    key = ws.cells(iRow,1)
    If arr.Exists(key) then
      sVal = arr.Item(key)
      ws.Cells(iRow, 5) = sVal(0)
      ws.Cells(iRow, 6) = sVal(1)
    End If
  Next
  writeData=true 
End Function

answered Jun 24, 2019 at 9:32

Whome's user avatar

WhomeWhome

10.1k6 gold badges52 silver badges64 bronze badges

You need to declare aarf as a regular variant not an array. The VBA will convert it for you.

Dim arrf As Variant

answered Sep 18, 2016 at 13:26

0

barsuuuk

0 / 0 / 0

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

Сообщений: 38

1

26.03.2018, 13:45. Показов 6373. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

имею:

Visual Basic
1
2
3
4
5
6
7
8
Private Sub UserForm_Click()
Dim ncolor As Byte
Dim mass01(11) As String
mass01 = Array("&H8000000F", "&H63ADD0", "&H9F69D6", "&HE467B3", "&HFD7279", "&HFF9D73", "&HFFCF73", "&HFFF273", "&HDBF970", "&HAEF26D", "&H62DA9A")
ncolor = ncolor + 1
If ncolor = 11 Then ncolor = 1
UserForm2.BackColor = mass(ncolor)
End Sub

ругается Can’t assign to array

что неверно у меня написано?
как правильно? гуглил, но безрезультатно, не разобрался



0



Остап Бонд

Заблокирован

26.03.2018, 14:09

2

Лучший ответ Сообщение было отмечено barsuuuk как решение

Решение

barsuuuk, одного гугла недостаточно, нужно и самому думать иногда —

Visual Basic
1
2
3
4
5
6
7
8
9
Private Sub UserForm_Click()
STATIC ncolor As Byte
Dim mass() 'As String
mass = Array("&H8000000F", "&H63ADD0", "&H9F69D6", "&HE467B3", "&HFD7279", "&HFF9D73", "&HFFCF73", "&HFFF273", "&HDBF970", "&HAEF26D", "&H62DA9A")
BackColor = mass(ncolor) 'mass01<>mass
ncolor = ncolor + 1
If ncolor = 11 Then ncolor = 0
'UserForm2.BackColor = mass(ncolor)
End Sub



1



1811 / 1134 / 345

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

Сообщений: 3,998

26.03.2018, 14:10

3

barsuuuk, строку 3 запишите так уже подсказали



0



0 / 0 / 0

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

Сообщений: 38

26.03.2018, 15:40

 [ТС]

4

Остап Бонд, Спасибо.

про STATIC был не в курсе.

в VBA въезжаю по мере необходимости на работе в течении последних недель 2х-3х, до этого никогда не пользовался.
Есть задача — надо сделать, знаний не хватает.
Стараюсь разбираться по мере возможностей.
когда уж не понимаю в чем дело — обращаюсь сюда.



0



MU-GK

31 / 28 / 1

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

Сообщений: 297

26.03.2018, 16:12

5

Тут дело не в статике, как я понимаю, просто задавать Аррай таким образом можно либо для свободных Аррай»ев, как Вам подсказали, либодлв переменных типа Вариант.
Т.е. можно было бы определить так:

Visual Basic
1
Dim mass As Variant



0



Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Can’t assign to an array

vblr6.chm1011081

vblr6.chm1011081

office

cc606f0f-7e50-c144-8003-90c7f976723d

06/08/2017

medium

Each element of an array must have its value assigned individually. This error has the following causes and solutions:

  • You inadvertently tried to assign a single value to an array variable without specifying the element to which the value should be assigned.

    To assign a single value to an array element, you must specify the element in a subscript. For example, if MyArray is an integer array, the expression MyArray = 5 is invalid, but the following expression is valid: MyArray(UBound(MyArray)) = 5

  • You tried to assign a whole array to another array.

    For example, if Arr1 is an array and Arr2 is another array, the following two assignments are both invalid:

        Arr1 = Arr2    ' Invalid assignment. 
        Arr1() = Arr2()    ' Invalid assignment. 

    To assign one array to another, make sure that the array on the left side of the assignment is resizable and the types of the array match.

    You can place a whole array in a Variant, resulting in a single variant variable containing the whole array:

           Dim MyArr As Variant 
           MyVar = Arr2() 

    You then reference the elements of the array in the variant with the same subscript notation as for a normal array, for example:

      MyVar(3) = MyVar(1) + MyVar(5) 

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Присвоение одного массива, другому (Сan’t assign to array)

Fidgy

Дата: Пятница, 07.06.2019, 18:18 |
Сообщение № 1

Группа: Пользователи

Ранг: Участник

Сообщений: 50


Репутация:

11

±

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


Excel 2016

Подскажите пожалуйста как решить эту проблему

Нужно в процедуре выбрать один из двух массивов, потом произвести множество алгоритмов именно с этим массивом, изменив его
Пытался сделать это через третий массив, но выходит ошибка Сan’t assign to array
Упрощённый пример кода:
[vba]

Код

Option Explicit
Dim ar1(1, 1) As Variant
Dim ar2(1, 1) As Variant

Sub test_ar()
ar1(1, 1) = 5
ar2(1, 1) = 10

test_arr2 1

MsgBox ar1(1, 1) & ar2(1, 1)
End Sub

Sub test_arr2(var As Byte)
Dim ar3() As Variant
Select Case var
    Case 1
    ar3 = ar1
    Case 2
    ar3 = ar2
End Select

ar3(1, 1) = ar3(1, 1) + 1

Select Case var
    Case 1
    ar1 = ar3
    Case 2
    ar2 = ar3
End Select
End Sub

[/vba]

 

Ответить

Pelena

Дата: Пятница, 07.06.2019, 19:35 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

Массивы обычно обрабатываются в цикле поэлементно.
Опишите задачу конкретнее, возможно, третий массив и не нужен


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

doober

Дата: Суббота, 08.06.2019, 09:28 |
Сообщение № 3

Группа: Друзья

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

Сообщений: 912


Репутация:

317

±

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


Excel 2010

Так работает[vba]

Код

Dim ar1() As Variant
Dim ar2() As Variant

Sub test_ar()
    ReDim ar1(1, 1)
    ReDim ar2(1, 1)
    ar1(1, 1) = 5
    ar2(1, 1) = 10
    test_arr2 1
    MsgBox ar1(1, 1) & ar2(1, 1)
End Sub

[/vba]


 

Ответить

Fidgy

Дата: Понедельник, 10.06.2019, 11:32 |
Сообщение № 4

Группа: Пользователи

Ранг: Участник

Сообщений: 50


Репутация:

11

±

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


Excel 2016

Pelena, ситуация в том, что у меня есть две таблице 10 на 10 в виде объектов UserForm
Данные об этих таблицах хранятся в двух массивах
Я предварительно выбираю с какой из двух таблиц буду работать и произвожу действие — на пример закрашиваю одну из ячеек и все соседние с ней
Данные о таблице №1 хранятся в массиве arr1(10, 10)
Данные о таблице №2 хранятся в массиве arr1(10, 10)

Далее говорю, что хочу закрасить ячейку по адресу 5, 3 и выбираю одну из двух таблиц

Пока нашел только вариант через дополнительную процедуру выбирать массив и затем передавать в процедуру обработки этот массив ByRef
[vba]

Код

Option Explicit
Dim ar1(1, 1) As Variant
Dim ar2(1, 1) As Variant

Sub test_ar()
ar1(1, 1) = 5
ar2(1, 1) = 10

test_arr2 1

MsgBox ar1(1, 1) & ar2(1, 1)
End Sub

Sub test_arr2(var As Byte)
Select Case var
    Case 1
    test_arr3 ar1
    Case 2
    test_arr3 ar2
End Select
End Sub

Sub test_arr3(ar3() as Variant)
ar3(1, 1) + 1
End Sub

[/vba]

 

Ответить

RAN

Дата: Понедельник, 10.06.2019, 12:08 |
Сообщение № 5

Группа: Друзья

Ранг: Экселист

Сообщений: 5645

Ничёнепонимаю!
Зачем все это? Чем по рабоче-крестьянски не устраивает?
[vba]

Код

Sub qq()
    Dim ar1, ar2
    ar1 = [a1:j10].Value
    ar2 = [a11:j20].Value
    Select Case [o1]
    Case 1: test ar1: [a1].Resize(10, 10).Value = ar1
    Case 2: test ar2: [a11].Resize(10, 10).Value = ar2
    End Select
End Sub
Sub test(ar)
   ar(5, 5) = ar(5, 5) * 5
End Sub

[/vba]


Быть или не быть, вот в чем загвоздка!

 

Ответить

Fidgy

Дата: Понедельник, 10.06.2019, 14:35 |
Сообщение № 6

Группа: Пользователи

Ранг: Участник

Сообщений: 50


Репутация:

11

±

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


Excel 2016

RAN, согласен, можно и так :)
Это уже издержки моего проекта, приходится создавать промежуточные сабы, иначе всё превращается в кашу и трудно контролировать

 

Ответить

InExSu

Дата: Суббота, 15.06.2019, 01:12 |
Сообщение № 7

Группа: Друзья

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

Сообщений: 646


Репутация:

96

±

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


Excel 2010

Привет!
[vba]

Код

Option Explicit
Private ar1(1, 1) As Variant
Private ar2(1, 1) As Variant

Public Sub REName_()
    ‘
    Dim ar3() As Variant

    ar3 = Массив_Выбрать(1)

End Sub

Public Function Массив_Выбрать(ByVal var As Long) _
        As Variant()
    ‘
    If var = 1 Then Массив_Выбрать = ar1
    If var = 2 Then Массив_Выбрать = ar2

End Function

[/vba]


Разработчик Битрикс24 php, Google Apps Script, VBA Excel

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Can sight word poem
  • Can sight word page
  • Can select text in word
  • Can see the future word
  • Can search in word document