VBA Error with Ubound when referring to 1 cell - arrays

I´m trying to understand the arrays in VBA, but I´m struggling a little bit, particularly with these lines. I can´t understand why, when the range I´m referring to is one or two cells, I get a mismatch error type 13 with the UBound.
Dim var2 As Variant
sArray2() As String
Dim i As Long
Dim range2 As Range
lastrow = Workbooks(Umsatzdatenbank).Sheets("Filter").Range("P" & _
Rows.Count).End(xlUp).Row
Set range2 = Workbooks(Umsatzdatenbank).Sheets("Filter").Range("P3:P" & _
lastrow)
var2 = range2.Value
ReDim sArray2(1 To UBound(var2))
For i = 1 To (UBound(var2))
sArray2(i) = var2(i, 1)
Next

When you assign the value of a single cell to a variable, the variable will be a single value, not an array. That's how Excel/VBA works, you cannot change this.
You can check if your variable var2 (not the best name for a variable IMHO), is an array or not and react to it, for example like:
var2 = range2.Value
If IsArray(var2) Then
ReDim sArray2(1 To UBound(var2))
For i = 1 To (UBound(var2))
sArray2(i) = var2(i, 1)
Next
Else
ReDim sArray2(1 To 1)
sArray2(1) = var2
End If

Related

Sorting cells by colour and putting their address into an Array

I am new to VBA. So usually I have to research stuff for my codes in order to make them work.
Now I am working on a code that has to get the values from cells with background colour that are different from -4142, and then putting those values in an array so that later I can insert those values in a dropdown list.
I was testing getting the values of the cells with different colours and putting them into arrays with the code I found in the answer of this question:
Appending a dynamic array in VBA
but for some reason, when I run the code I get the error 13 incompatible types (I don't know if the error message is that in english because my vba is in another language, but the error number is 13 non the less), in the line myArray(X) = cell.Address
It may be very silly but I dont know what to do.
Sub SelectByColor()
Dim cell As Range
Dim rng As Range
Dim LR As Long
Dim myArray() As Double, X As Long
X = 0
'For understanding LR = Last Row
LR = Range("B:B").SpecialCells(xlCellTypeLastCell).Row
ReDim Preserve myArray(X)
Set rng = Range("B2:B" & LR)
For Each cell In rng.Cells
If cell.Interior.ColorIndex <> -4142 Then
myArray(X) = cell.Address
X = X + 1
If X < N Then ReDim Preserve myArray(0 To X)
mystr = mystr & cell.Address & ","
End If
Next cell
mystr = Left(mystr, Len(mystr) - 1)
MsgBox mystr
MsgBox myArray(X)
End Sub
The mystr part is to see if the code would be getting the correct values, and it is, but it is not appending in the array.
(a) You get your runtime error because you declares your array to hold numbers, but you are trying to write addresses (=strings) into it. An cell address (eg $A$1) cannot be converted into a number and therefore VBA throws that error 13.
(b) A list of values used as Data Validation can be created by a range of cells or by a (hardcoded) list of values. However, the range need to be contiguous, which is not the case for your requirements.
So what you need is a list of values. The values need to be separated by ",". You can do the by creating an array as you do in your code and then use the Join-function. However, the array needs to be of type String or Variant, it will not work with Double.
As I don't like to use Redim Preserve in a Loop (very inefficient), I changed the logic by sizing the array with the maximum of possible values (LR) and then use only a single Redim to remove unused entries after the values are filled.
ReDim myArray(LR)
Dim X As Long, rng as Range, cell as Range
Set rng = ActiveSheet.Range("B2:B" & LR)
For Each cell In rng.Cells
If cell.Interior.ColorIndex <> -4142 and not isError(cell.value) Then
myArray(X) = cell.Value
X = X + 1
End If
Next cell
Redim Preserve myArray(X) ' Remove unused entries
Set the validiation:
With Selection.Validation ' <-- Replace Selection with the Range where you want to apply the validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=Join(myArray, ",")
End With

multi dimensional array with different elements; VBA excel

Is it possible to create multi dimensional array with different element types (string and integer)?
I tried like this but wan't work
BT = Range("A12")
ReDim IT(BT) As String
ReDim RBT(BT) As Integer
ReDim IT_RBT(IT, RBT) as ???? how to create multi dim array with different variables type
Range("B2").Select
i = 0
Do
i = i + 1
IT(i) = ActiveCell
RBT(i) = i
IT_RBT(i, i) = ???? how to enter values in such array ????
ActiveCell.Offset(1, 0).Select
Loop While ActiveCell <> ""
Thank you
Use a Variant array.
Dim values() As Variant
Now, your code is making assumptions that should be removed.
BT = Range("A12") '<~ implicit: ActiveSheet.Range("A12").Value
If you mean to pull the value of A12 from a particular specific worksheet, then you should qualify that Range member call with a proper Worksheet object. See CodeName: Sheet1 for more info, but long story short if that sheet is in ThisWorkbook you can do this:
BT = Sheet1.Range("A12").Value
And now assumptions are gone. Right? Wrong. BT isn't declared (at least not here). If it's declared and it's not a Variant, then there's a potential type mismatch error with that assignment. In fact, the only data type that can accept any cell value, is Variant:
Dim BT As Variant
BT = Sheet1.Range("A12").Value
Here, we're assuming BT is a numeric value:
ReDim IT(BT) As String
That's another assumption. We don't know that BT is numeric. We don't even know that it's a value that can be coerced into a numeric data type: we should bail out if that's not the case:
If Not IsNumeric(BT) Then
MsgBox "Cell A12 contains a non-numeric value; please fix & try again."
Exit Sub
End If
ReDim IT(BT) As String
Now that will work... but then, only the upper bound is explicit; is this a 0-based or a 1-based array? If the module says Option Base 1, then it's 1-based. Otherwise, it's 0-based - implicit array lower bounds are an easy source of "off-by-one" bugs (like how you're populating the arrays starting at index 1, leaving index 0 empty). Always make array bounds explicit:
ReDim IT(1 To BT) As String
Unclear why you need 3 arrays at all, and why you're only populating (i,i) in the 3rd one - you cannot populate a 2D array with a Do...Loop structure; you need every value of y for each value of x, and unless you hard-code the width of the array, that's a nested loop.
Moreover, looping on the ActiveCell and Selecting an Offset is making the code 1) very hard to follow, and 2) incredibly inefficient.
Consider:
Dim lastRow As Long
lastRow = Sheet1.Range("B" & Sheet1.Rows).End(xlUp).Row
ReDim values(1 To lastRow, 1 To 2) As Variant
Dim currentRow As Long
For currentRow = 2 To lastRow
Dim currentColumn As Long
For currentColumn = 1 To 2
values(currentRow, currentColumn) = Sheet1.Cells(currentRow, currentColumn).Value
Next
Next
Now, if we don't need any kind of logic in that loop and all we want is to grab a 2D variant array that contains every cell in B2:B???, then we don't need any loops:
Dim values As Variant
values = Sheet1.Range("A2:B" & lastRow).Value
And done: values is a 1-based (because it came from a Range), 2D variant array that contains the values of every cell in A2:B{lastRow}.
Note, code that consumes this array will need to avoid assumptions about the data types in it.
As #SJR has said, variant will allow for this. The below example is a easy example how to add different types to an array. Instead of x or y you can have a cell on a worksheet.
Dim array1() As Variant, i As Long
Dim x As String, y As Long
x = "5"
y = 1
For i = 1 To 10
ReDim Preserve array1(1 To 2, 1 To i)
array1(1, i) = x
array1(2, i) = y
y = y + 1
Debug.Print array1(1, i) & "," & array1(2, i) ' This is where you insert output
Next
You can do this:
BT = Range("A12")
ReDim IT(BT) As String
ReDim RBT(BT) As Integer
Dim IT_RBT(1 to 2) 'variant
IT_RBT(1) = IT 'add String array
IT_RBT(2) = RBT 'add Integer array
... this will keep your typed arrays functional but it's not a 2D array and you'd need to use notation like
IT_RBT(1)(1) 'String type
IT_RBT(2)(1) 'Integer type

Using VBA to assign range of cell values to array of variables

I'm very new to VBA, to bear with me here.
I want to assign a set of variables the value of a set of ranges ie. run a brief code to simplify the following
Dim Sample 1 as string
Sample1 = activeworksheet.range("C17").value
Dim Sample 2 as string
Sample2 = activeworksheet.range("C18").value}
and so on
Following an excelfunctions.net tutorial, I know that I can shorten the declaration to
Dim Sample(1 to 20) as a string
But the tutorial drops it there(because it's a tutorial about names), suggesting I populate it as follows
sample(1)=activesheet.range("C7").value
sample(2)=activesheet.range("C7").value
and so on
I found the discussion below to be on the right track to answer my quest, but I am having trouble applying it to my situation. (Excel VBA Array Ranges for a loop)
As a follow up note, I am ultimately trying to assign values to these variables for use in the following procedures, rather than declaring and assigning them each time.
Thanks!
Try something like this:
Sub test()
Dim sampleArr(1 To 20) As String
Dim i As Integer
Dim rng As Range, cel As Range
i = 1
Set rng = Range("C1:C20")
For Each cel In rng
sampleArr(i) = cel.Value
i = i + 1
Next cel
For i = LBound(sampleArr) To UBound(sampleArr)
Debug.Print sampleArr(i)
Next i
Also, if you know the range you want to put into an array, you can simply set an array to that range:
Sub test()
Dim sampleArr() As Variant
Dim i As Integer
Dim rng As Range, cel As Range
i = 1
Set rng = Range("C1:C20") ' Note, this creates a 2 Dimensional array
sampleArr = rng ' Right here, this sets the values in the range to this array.
For i = LBound(sampleArr) To UBound(sampleArr)
Debug.Print sampleArr(i, 1) ' you need the ",1" since this is 2D.
Next i
End Sub
You should :
Define the range you want to retrieve data
For each cell of the range, retrieve your datas
dim tab() As string, cell as range, i as integer
i = 0
redim tab(0)
for each cell in ActiveWorksheet.Range("C1:C20")
tab(i) = cell
i = i + 1
redim preserve tab(i)
next
edit : I indent the code to display it correctly
Additional way to the above you can only use:
Arr = ActiveWorksheet.Range("C1:C20").Value
Then you can directly use:
Arr(i,1) where i is C1 to C20 range!

Excel VBA: Cant add to an array?

I have run into a problem, im fairly new to VBA but learning fast. I have been trying to right this code below, to look through a column and pick out all the possible values that rows of data take in this column for use in another bit of code.
I cant get the array to work, i could just be doing it wrong.
In case its not clear, it should check the value of a cell in column I and if it is a value (and if it hasnt been stored already (code shown but not used yet)) then the value is stored in the array and the position in the array and the position down the column incremented.
Another question i havent looked at yet is then how to arrange the values in the array by name etc? The values in this case will be AHU1, AHU2, AHU3 etc up to about AHU5 or 6, I also intend to implent a bit of code that will expand the Array if necassery (from smaller so it is not bigger than it needs to be)
EDIT: another problem i havnt worked out yet is why the If statement always causes the value to be added to the array (which it doesnt)
Do
If IsNull(V1.Range("I" & i)) = False Then 'And V1.Range("I" & i).Value <> (Val(AHUArray(1)) Or Val(AHUArray(2)) Or Val(AHUArray(3)) Or Val(AHUArray(4)) Or Val(AHUArray(5)) Or Val(AHUArray(6)) Or Val(AHUArray(7)) Or Val(AHUArray(8)) Or Val(AHUArray(9)) Or Val(AHUArray(10))) Then 'And (does not equal any other values in the array
AHUArray(ArrayDim) = V1.Range("I" & i).Text
i = i + 1
ArrayDim = ArrayDim + 1
Else
i = i + 1
End If
Loop While i <= LastRow
Any ideas?, help will be greatly appreciated!
These are the definitions from before this code encase its a probloem with these (as it has been in the past but i dont think it is?
Dim V1 As Worksheet
Dim LastRow As Long
Dim C As Range
Dim FirstAddress As String
Dim AHUArray(1 To 10) As String
Dim DestCell As Integer
Dim i As Integer
Dim ArrayDim As Integer
Set V1 = ThisWorkbook.Sheets("V1")
Set AHU = ThisWorkbook.Sheets("AHU")
LastRow = V1.Range("A:A").Find("*", V1.Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
DestCell = 3
ArrayDim = 1
i = 3
Change
IsNull(V1.Range("I" & i)) = False
to
V1.range("I" & i).value <> ""
When you use IsNull like that you are always going to get true, because you are asking, "is this range value which I just created and defined Null?"
Regarding dynamically growing the array, see this answer for examples on how to do so.
In the end this is how i managed it. Realised using IsNull was foolish, and managed to make a check function using how UBound returns -1 is it doesnt find anthing
Do
If IsEmpty(V1.Range("I" & i)) = False And IsInArray(V1.Range("I" & i).Value, AHUArray) = False Then '(does not equal any other values in the array
AHUArray(ArrayDim) = V1.Range("I" & i).Value
i = i + 1
ArrayDim = ArrayDim + 1
Else
i = i + 1
End If
Loop While i <= LastRow
and this is the other check function
Function ArrayCountIs(ArrayToCount As Variant) As Integer
Dim i As Integer
Dim ArrayCount As Integer
ArrayCount = 0
i = 0
For i = LBound(ArrayToCount) To UBound(ArrayToCount)
If Not (ArrayToCount(i)) = "" Then
ArrayCount = ArrayCount + 1
End If
Next
ArrayCountIs = ArrayCount
End Function

Ms Excel -> 2 columns into a 2 dimensional array

Im coming from a Unix world where I never had to develop something for Office with VBA, I have to do some now and Im having a hard time! Please help me! :)
So I've got 2 Excel Sheets(lets call them Sheet1 and Sheet2) and 2 forms(Form1 and Form2) to edit/add data.
In Sheet1, the first two columns are MovieId and MovieName. We dont know how many rows they will be in this columns.
Form1 controls data in Sheet1, and Form2... in Sheet2.
At Form2 initialization, I want to create a 2 Dimensional Array that will be like (MovieId1,MovieName1;MovieId2,MovieName2;...,...;MovieIdN,MovieNameN), where this data has been extracted from Sheet1, like a sort of Map in Java if you will...
It would actually be ok for me if it was like: (0,"MovieId0;MovieName0";1,"MovieId1,MovieName1";..,"..";N,"MovieIdN,MovieNameN")
I dont know how to create the array with an variable last row number, since the compiler seems to always want a constant to initialize an Array...
Please enlighten me!
Look at the Value method or Value2 property.
e.g. Range("$A$2:$B$4").Value2(1,1)
or
Range("$A$2:$B$4").Value()(1,1)
Array's lower bound start from 1.
lbound(Range("$A$2:$B$4").Value2, 1) - row element starts from
ubound(Range("$A$2:$B$4").Value2, 2) - row element ends
lbound(Range("$A$2:$B$4").Value2, 2) - column element starts from
ubound(Range("$A$2:$B$4").Value2, 2) - column element ends
EDIT: Code to traverse through the array
Dim myAddress As String
Dim dataArray As Variant
Dim rowStart As Long, rowEnd As Long
Dim colStart As Long, colEnd As Long
Dim rowCtr As Long
Dim colCtr As Long
myAddress = "$A$2:$B$4"
dataArray = Range(myAddress).Value2
rowStart = LBound(dataArray, 1)
rowEnd = UBound(dataArray, 1)
colStart = LBound(dataArray, 2)
colEnd = UBound(dataArray, 2)
For rowCtr = rowStart To rowEnd
For colCtr = colStart To colEnd
Debug.Print rowCtr & ":" & colCtr, vbTab & dataArray(rowCtr, colCtr)
Next
Next
EDIT2: In my example, I have assumed the address to be $A$2:$B$4.
You can prefix it with sheet name. e.g. Sheet1!$A$2:$B$4 or Sheet2!$A$2:$B$4
On a side note, array can be defined dynamic (if it is 1 dimensional).
e.g dim my1DArray() as Integer
For double dimension array, see the following code
Dim myArray
Dim dynamicRows As Integer
dynamicRows = 2
ReDim myArray(0 To dynamicRows, 0 To dynamicRows)
myArray(0, 0) = "hello"
dynamicRows = 20
ReDim myArray(0 To dynamicRows, 0 To dynamicRows)
MsgBox myArray(0, 0)
myArray(0, 0) = "hello"
ReDim Preserve myArray(0 To dynamicRows, 0 To dynamicRows)
MsgBox myArray(0, 0)
Rather use the Range object, with this you can also use the UsedRange from the sheet
Sub Macro1()
Dim sheet As Worksheet
Dim range As range
Dim row As Integer
Set sheet = Worksheets("Sheet1")
Set range = sheet.UsedRange
For row = 1 To range.Rows.Count
Next row
End Sub
assuming the data starts in A1
Dim vArr as variant
vArr=worksheets("Sheet1").range("A1").resize(worksheets("Sheet1").range("A65535").end(xlup).row,2)
Do you mean:
Dim thearray() As Variant
ReDim thearray(1, range.Rows.Count)
You can also use a recordset and GetRows to return an array from a worksheet.
Slight mod to Charles' answer:
Dim vArr as variant
vArr = Worksheets("Sheet1").Range("A1").CurrentRegion.Value
Assuming of course that there isn't any stray data in Sheet1.

Resources