简体   繁体   中英

Creating an array from a range of cells in Excel VBA

The following is pretty much identical to the solutions online that I've found:


Dim iAmount() As Variant
Dim INum As Integer

iAmount = Range("C23:W23")
'The example uses iAmount = Range("A1:A11")

For iNum = 1 to Ubound(iAmount)
Debug.Print iAmount(iNum,1)
Next iNum

End Sub

However when I try to work with this array I get error 9 which I interpret to mean that I referenced a variable that doesn't exist.

You are reading the rows instead of columns which is why your code doesn't work. Your range is composed of 1 row and 21 columns.

You can read the columns like this:

For INum = LBound(iAmount, 2) To UBound(iAmount, 2)
  Debug.Print iAmount(1, INum)
Next INum

The correct way to read any full range is like this:

Dim i As Long, j As Long
For i = LBound(iAmount, 1) To UBound(iAmount, 1)  ' rows
    For j = LBound(iAmount, 2) To UBound(iAmount, 2) ' columns
        Debug.Print iAmount(i, j)
    Next j
Next i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM