Home » excel » excel – Assigning a specific cell from a Range to a variable VBA

excel – Assigning a specific cell from a Range to a variable VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

Is there a way to store specific cells into new variables from a range in VBA? What I mean is…

Suppose I have set the data below to a range call “numbers”.

enter image description here

Now in VBA, for each row I want to extract each individual cell value and assign each value to a different variable. And then repeat again for the next row.

I essentially want to the use the values in a given row to do something and then have it repeat again for the next row.

Does this make sense???

This is what I’ve been playing around with… but I don’t get how to assign each cell from a given row to a new variable

Public Sub try()
    Dim rng As Range
    Dim row As Range
    Dim cell As Range
    Dim n As Double

    Set rng = Range("numbers")

    For Each row In rng.Rows

        For Each cell In row.Cells

              n = cell.value

        Next cell

    Next row
End Sub
How to&Answers:

Try this:

Dim numberArray As Variant
' this line will assign numbers inside the range to an array
numberArray = Range("numbers").Value2
' now you are able to access all numbers in you range through this array, like this:
MsgBox numberArray(1, 1) 'it will show 1

The way you are doing it right now doesn’t make sense, since you are assigning all values to one variable n, so on every iteration of a loop previous value gets overwritten, resulting in n having last value in a range, which is 3.

Answer:

Is there any particular reason you want to store any cell value in a new variable?
With a given range it would be very easy to just store your values in a Variant Array. In your example it would be something like:

Public Sub try()

    Dim rng As Range
    Dim dataArray as Variant

    Set rng = Range("numbers")
    dataArray = rng

    debug.print dataArray(1, 2) 'This would print 7 in your example range

end sub

You could then easily loop through your Variant Array like this:

Dim i as Long, j as Long

For i = 1 To UBound(dataArray, 1) 'This will loop through each row
    For j = 1 To UBound(dataArray, 2) 'This will loop through each column (cell in your row)
        Debug.Print dataArray(i, j)
    Next
Next

UBound() returns the length of the Array at the given dimension as the second parameter. I am just printing the values again since I do not know what exactly your intention is.