简体   繁体   中英

Loading single value to VBA array

I've been running a VBA code in Excel 2016 that loads a bunch of values into array from a single-column Excel table and then runs a FOR-loop on each value.

Sub Load_array()

Dim x As Long
Dim myArray() As Variant
Dim myTable As ListObject

Set myTable = Sheets("Sheet1").ListObjects("Table1")
TempArray = myTable.DataBodyRange.Columns(1)

myArray = Application.Transpose(TempArray)

For x = LBound(myArray) To UBound(myArray)

Range("A1").Value = myArray(x)

Next x

End Sub

Works fine up until I found a "bug". In case there is only a single row in that DataBodyRange, I'll get an error:

myArray = Application.Transpose(TempArray)

"Run time error '13': Type mismatch"

I could use a worksheet-based Excel COUNTA -formula and add IF-clause to re-route the code in case there is only a single value to be loaded, however perhaps there's a more elegant way to handle this? My experience on working with arrays is not extensive at all, so perhaps you guys could guide me a little?

Transposing a single-value array does not work like that, right?

Check if it's an array or exit.

Sub Load_array()

Dim x As Long
Dim myArray() As Variant
Dim TempArray
Dim myTable As ListObject

Set myTable = Sheets("Sheet2").ListObjects("Table1")
TempArray = myTable.DataBodyRange.Columns(1)
If Not IsArray(TempArray) Then '<~~ Check array
    Range("a1") = TempArray
    Exit Sub
End If

myArray = Application.Transpose(TempArray)

For x = LBound(myArray) To UBound(myArray)

    Range("A1").Value = myArray(x)

Next x

End Sub

Or force the single value into an array so it can be processed consistently ...

Option Explicit

Public Sub Load_array()

    Dim myRange As Range
    Dim myArray
    Dim x As Long

    Set myRange = Worksheets("Sheet1").ListObjects("Table1").ListColumns(1).DataBodyRange
    myArray = IIf(myRange.Rows.Count = 1, Array(myRange), Application.Transpose(myRange))

    For x = LBound(myArray) To UBound(myArray)
        Range("A1").Value = myArray(x)
    Next x
End Sub

ref: Force the creation and "looping" of single element arrays? (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.

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