I have some data in terms of a column that I want to store into an array using VBA. After storing it, I will reference the element in the array and make a comparison.
Dim tRange As Range
Set tRange = wb.Sheets("wbname").Range("A1:A5")
Lets say I want to store column A
with 5 row into the array in VBA. May I know the way?
Here is one way:
Sub Dave()
Dim tRange As Range, wb As Workbook, cell As Range
Dim i As Long
Set wb = ThisWorkbook
Set tRange = wb.Sheets("wbname").Range("A1:A5")
ReDim arr(1 To tRange.Count)
i = 1
For Each cell In tRange
arr(i) = cell.Value
i = i + 1
Next cell
End Sub
NOTE:
This technique does not depend on the "shape" of the range. It will work if the range is a piece of a column, or a piece of a row, or a rectangle of cells, or even a disjoint set of cells.
You can just declare a Variant data type and make it equal to the range.
Dim DirArray As Variant
DirArray = Range("a1:a5").Value
This was answered in a previous question by @vacip coincidentally for exactly the same range! Creating an Array from a Range in VBA
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.