I would like to know if it is possible to loop through a multi-dimensional array and limit the loop to the first dimension only.
I have worked out an example to ilustrate my point:
I use the data I have in excel to create a matrix and I want the loop to print only the values that correspond to the Index column. I have tried different things but nothing seems to work except when using if conditions to exit the for loop.
Here is the original code:
Public matrix1() As Variant
Sub elements_in_loop()
Range("A3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix1 = Selection
For Each Record In matrix1
Debug.Print Record
Next
End Sub
here is the code with an if condition:
Public matrix1() As Variant
Sub elements_in_loop()
Range("A3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix1 = Selection
For Each Record In matrix1
If Record <= UBound(matrix1) Then
Debug.Print Record
Else:
Exit For
End If
Next
End Sub
Any advice on how to do it without an if condition is much appreciated.
Update:
What I need this information for is to look for similar records in two matrices without getting the error "Type mismatch".
Here's the data I'm using:
The record in yellow is the one that is in both matrices.
Here is the code I've worked out to get the records that match but is still using if conditionals to limit the search to the first dimension only.
Public matrix1() As Variant
Public matrix2() As Variant
Sub elements_in_loop()
Range("A3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix1 = Selection
Range("G3").Select
Range(Selection.End(xlToRight), Selection.End(xlDown)).Select
matrix2 = Selection
For Each Record In matrix1
If Record <= UBound(matrix1) Then
For Each Record2 In matrix2
If Record2 <= UBound(matrix2) Then
If matrix1(Record, 4) = matrix2(Record2, 4) Then
Debug.Print "There's match"
Debug.Print Record
Else: End If
Else:
Exit For
End If
Next
Else:
Exit For
End If
Next
End Sub
ForLoopFor i = Lbound(Matrix,1) to Ubound(Matrix,1)then you would refer to the itemDebug.Print Matrix(i,1)