∟"Type mismatch" Runtime Error - Assignments to Array Variables

This section describes how values from scalar array variables can be assigned to other scalar or array variables. Runtime error 'Type mismatch' happens when you try to assign scalar values or arrays to array variables.

After learning two types of variables: scalar variable and array variable,
let's review and summarize how assignment operation works with both types in this section.

1. Can you assign the value of a scalar variable to another scalar variable?
The answer is simple: "Yes". For example:

another_scalar_variable = scalar_variable

A copy of the value in "scalar_variable" will be assigned to "another_scalar_variable"

2. Can you assign the value of a scalar variable to an array variable?
The answer is simple: "No". For example:

array_variable = scalar_variable

If you try it, you will get a runtime error: Type mismatch.

3. Can you assign the value of an array variable to a scalar variable?
The answer is not so simple.

Technically, a scalar variable is not capable to store an array.
So the answer is no - you can not assign an array directly to a scalar variable.

But a scalar variable can be used to store a reference, or a pointer, of an array.
So the answer is yes - you can assign an array indirectly to a scalar variable.
For example:

scalar_variable = array_variable

The assignment operation will first create a new dynamic-size array as a copy of the specified array.

The assignment operation will then create a reference of the new dynamic-size array.

Finally, the reference of the new dynamic-size array is stored into the specified scalar variable.

4. Can you assign the value of an array variable to another array variable?
The answer is simple: "No". For example:

another_array_variable = array_variable

If you try it, you will get a runtime error: Type mismatch.

Try to play with the following example to understand
how assignment operation works with scalar variables and array variables:

<html>
<body>
<!-- array_type_mismatch.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
Dim aScalar
Dim anotherScalar
Dim anArray(9)
Dim anotherArray(9)
anotherScalar = aScalar 'Creates a copy of aScalar's value
anArray = aScalar 'Runtime error: Type mismatch
aScalar = anArray 'Creates a copy of anArray's array
anotherArray = anArray 'Runtime error: Type mismatch
</script>
</pre>
</body>
</html>