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]
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.
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.
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.
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.
If a Variant array is OK:
Dim cols()
cols = [{2,3,5,6,7,9,10,13,14,15,16}]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With