VBA: How to avoid 'Run-time scenarios 9: Subscript out of range' when accessing multi-dimensional arrays?
I'm building a feature where This might be a silly question, but I'm sure I'm missing something obvious here, but I'm working with a multi-dimensional array in VBA to store data from a sheet called "DataSheet". The array is defined to hold data for multiple categories, but I'm working with a 'Run-time behavior 9: Subscript out of range' when I try to access a specific index. After setting up the array and populating it with values, I loop through the data and try to reference it as follows: ```vba Dim myArray() As Variant Dim i As Long, j As Long ' Assuming data starts from A1 and has 10 rows and 5 columns ReDim myArray(1 To 10, 1 To 5) For i = 1 To 10 For j = 1 To 5 myArray(i, j) = Worksheets("DataSheet").Cells(i, j).Value Next j Next i ' Trying to access a specific value Debug.Print myArray(11, 1) ' This line triggers the behavior ``` I realized that I'm trying to access an index (11, 1) that is out of the bounds of my array which is defined from 1 to 10 for the first dimension. However, what confuses me is that I thought I had handled the array dimensions correctly. I've already tried to check the dimensions of `myArray` with `UBound(myArray, 1)` and `UBound(myArray, 2)`, which returns 10 and 5 respectively. I would like to know how to properly handle such scenarios when dynamically working with arrays, especially when the data size can vary. Should I include additional checks before accessing array elements? What are best practices for working with multi-dimensional arrays in VBA to avoid these runtime errors? My development environment is macOS. Am I missing something obvious? Could someone point me to the right documentation?