0

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?

1
  • There's no real shortcut here - you will need an If to take a separate route if there's only one cell. Commented Feb 3, 2020 at 1:27

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Although the previous answer solved my problem and felt easier to follow, I appreciate the input and will review this. Given I don't actually want to kill the Sub with single-value array but rather still process it, this one feels more efficient - once I'll get my head around it. Extra link surely helps too. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.