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
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:
- We should assign values to each element of an array separately or one-by-one using the array’s indexes
- 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.”
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
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.
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.
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:
- What the datatype should be for the array on the left side of the assignment statement
- What should be the size of the array
- 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
32.9k6 gold badges26 silver badges51 bronze badges
asked Sep 18, 2016 at 12:55
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
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 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
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 Метки нет (Все метки)
имею:
ругается Can’t assign to array что неверно у меня написано?
0 |
Заблокирован |
||||
26.03.2018, 14:09 |
2 |
|||
Сообщение было отмечено barsuuuk как решение Решениеbarsuuuk, одного гугла недостаточно, нужно и самому думать иногда —
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 |
|||
Тут дело не в статике, как я понимаю, просто задавать Аррай таким образом можно либо для свободных Аррай»ев, как Вам подсказали, либодлв переменных типа Вариант.
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 expressionMyArray = 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 andArr2
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) |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |