Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to assign values to an Option Base 1 array in VBA using a single line?

Tags:

arrays

excel

vba

I am assigning integers (11 in total) to an array with index 1 to 11, one index at a time.

Is there a way to do it in one line, similar to how it is done for example in Matlab.

How I am doing it now:

Dim cols(1 To 11) As Integer

cols(1) = 2
cols(2) = 3
cols(3) = 5
cols(4) = 6
cols(5) = 7
cols(6) = 9
cols(7) = 10
cols(8) = 13
cols(9) = 14
cols(10) = 15
cols(11) = 16

How I would like to do it:

Dim cols(1 To 11) As Integer

cols = [2,3,5,6,7,9,10,13,14,15,16]

I am aware that it can be done without defining the variable as an array, but that returns the array with index 0 to 10:

Dim cols As Variant

cols = Array(2,3,5,6,7,9,10,13,14,15,16]
like image 401
Johannes Veje Avatar asked Sep 15 '16 11:09

Johannes Veje


People also ask

How do I assign a value to an array in VBA?

Dim wb As Workbook Set wb = ThisWorkbook 'for the workbook containing the code Set wb = Workbooks(workbookName) 'to reference an other Workbook 'And for all the sheets you are using Dim ws As Worksheet Set ws = wb.

How do you assign a value to an array element?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

What does Option Base 1 do in VBA?

VBA VBA Option Keyword Option Base {0 | 1} Option Base is used to declare the default lower bound of array elements. It is declared at module level and is valid only for the current module.

How do you assign a range of cells to an array in VBA?

Steps to Add a Range into an Array in VBA First, you need to declare a dynamic array using the variant data type. Next, you need to declare one more variable to store the count of the cells from the range and use that counter for the loop as well. After that, assign the range where you have value to the array.


2 Answers

If a Variant array is OK:

Dim cols()
cols = [{2,3,5,6,7,9,10,13,14,15,16}]
like image 95
Rory Avatar answered Sep 22 '22 05:09

Rory


If you are okay with two lines instead of one line, you can try this:

Dim cols As Variant

cols = Array(2,3,5,6,7,9,10,13,14,15,16)
ReDim Preserve cols(1 To UBound(cols) + 1)
like image 22
SandPiper Avatar answered Sep 21 '22 05:09

SandPiper