Understanding Retrieving and Storing VBA Values in an Array

Asked 2 years ago, Updated 2 years ago, 323 views

The following code is used to store cell values in an array, but when I checked Debug.Printary(j,1), it seems that the values are not displayed (not retrieved).

ary=Array (Cells(j, "E").Value, Cells(j, "F").Value, Cells(j, "G").Value, Cells(j, "H").Value, Cells(j, "I").Value)

What is wrong with the code below?There are no errors.

 Dim j As Long
Primary As Variant

For j=1 To LastRow
    If Cells(j, "J").Value="JST" Then
        aary=Array (Cells(j, "E").Value, Cells(j, "F").Value, Cells(j, "G").Value, Cells(j, "H").Value, Cells(j, "I").Value)
        Debug.Printary(j,1)
    End If
Next

vba

2022-09-30 22:05

1 Answers

What is wrong with the code below?There are no errors.

Debug.Printary(j,1) should get an "Index Not in Valid Range" error.
OnError Resume NextIs there a code somewhere that ignores this error?If so, let's comment it out first.

The reason for the error is that the Array function returns a one-dimensional array, so aary is a one-dimensional array.
Nevertheless, we treat it as a two-dimensional array with ary(j,1), which results in the above error.

Debug.Printary(0)
displays the first value of the array (=Cells(j, "E").Value).

If you want to put the first row of columns E through I into an array, you can do it in one row below without looping.

Dim LastRow As Long
   LastRow=Cells(Rows.Count, "E").End(xlUp).Row

   Primary() As Variant
   aary=Range(Cells(1, "E"), Cells(LastRow, "I")).Value

   US>'Check the first column (column E) value of the array
   Dimi
   Fori=1 to LastRow
       Debug.Printary(i,1)
   Next

By the way, the array substituted with Value as shown above starts with an index of 1.
The Array function starts with 0.


2022-09-30 22:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.