arraysexcelvbavariant

Getting the values for the cells if there is 1 or more values assigned


How do I fix this if I have cells having values for 2 or more for SHEET1 in columns A & B with this code: (I don't have any problems)

Dim LineNumbers() As Variant
LineNumbers = Range("A1", ActiveSheet.Cells(Rows.Count, "A").End(xlUp))
Dim Lengths() As Variant
Lengths = Range("B1", ActiveSheet.Cells(Rows.Count, "B").End(xlUp))      

But if there is only 1 value for the row on columns A & B this raises an error. I read here that if I use usedrange, CountA and xldown is not recommended to get the last used row as it causes some errors for the results, then the code above is much efficient. Unfortunately for me when I have only 1 value in my LineNumbers and Lengths this raises an error.


Solution

  • Writing From a Range to an Array

    Dim LineNumbers As Variant
    Dim Lengths As Variant
    
    With ActiveSheet
        With .Range("A1", .Cells(.Rows.Count, "A").End(xlUp))
            If .Rows.Count = 1 Then ' one cell
                ReDim LineNumbers(1 To 1, 1 To 1): LineNumbers(1, 1) = .Value
            Else ' multiple cells
                LineNumbers = .Value
            End If
        End With
        With .Range("B1", .Cells(.Rows.Count, "B").End(xlUp))
            If .Rows.Count = 1 Then ' one cell
                ReDim Lengths(1 To 1, 1 To 1): Lengths(1, 1) = .Value
            Else ' multiple cells
                Lengths = .Value
            End If
        End With
    End With