Home » excel » excel – Accessing the value in a range.areas(2)

excel – Accessing the value in a range.areas(2)

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am saving a range to an array in VBA. Works unless I have multiple areas in the range, then only the first area is converted to the array and the second area is ignored.

When I look at Locals Window I can find the values of the range in the Item 2 section of the Areas portion of the range object.

I tried to make a union between the two range areas, but the result still leaves me with a range with areas and does not work when I apply it to the array. I tried accessing these values in the ‘Item 2’ section of the range object but I cannot figure out how to reach them.

Sub Main()
    Dim InputRange As Range

    Set InputRange = Union(Sheets("VialHelper").Range("H91:GY94"), 
    Sheets("VialHelper").Range("H145:GY145"))
    Call ArrayBuilder(AwesomeArr(), InputRange)

End Sub


Sub ArrayBuilder(ByRef finArray() As Variant, RangeArr As Range)

    Dim tempArray As Variant
    Dim i As Integer, j As Integer, counter As Integer
    Dim area As Range

    counter = 1
    tempArray = RangeArr 'HERE IS WHERE I NEED THE SECOND AREA TO BE ADDED TO THE ARRAY


    ReDim finArray(1 To 2)
    For i = LBound(tempArray, 1) To UBound(tempArray, 1)
        For j = LBound(tempArray, 2) To UBound(tempArray, 2)
            If Left(tempArray(i, j), 2) = "L0" Or Left(tempArray(i, j), 2) = "R0" Then
                ReDim Preserve finArray(1 To counter)
                finArray(counter) = tempArray(i, j)
                counter = counter + 1
            End If
        Next j
    Next i

End Sub

I expect to see all values from the areas defined in the range to be in the tempArray variable. But I only see the values from area 1.

How to&Answers:

You need to iterate the areas one way or another.

Perhaps something like this:

Sub ArrayBuilder(ByRef finArray() As Variant, ByVal RangeArr As Range)

    Dim tempArray() As Variant
    Dim i As Long, j As Long, counter As Long

    counter = 1
    ReDim finArray(1 To 2) ' not sure why you do this

    Dim area As Range
    For Each area In RangeArr.Areas
        If area.Count = 1 Then
            ReDim tempArray(1 To 1, 1 To 1)
            tempArray(1, 1) = area.Value
        Else
            tempArray = area.Value
        End If

        For i = LBound(tempArray, 1) To UBound(tempArray, 1)
            For j = LBound(tempArray, 2) To UBound(tempArray, 2)
                If Left(tempArray(i, j), 2) = "L0" Or Left(tempArray(i, j), 2) = "R0" Then
                    ReDim Preserve finArray(1 To counter)
                    finArray(counter) = tempArray(i, j)
                    counter = counter + 1
                End If
            Next j
        Next i
    Next area

End Sub