SNA14
SNA14

Reputation: 33

How to return multiple values in an Array - Excel VBA

I am trying to return multiple values stored in an array. [Image of array] I'm not really sure how to describe it, but what i want to do is output the values like 0 in A1, 37.2 in B1, 5.51 in C1, 0.498 in D1, 4.17 in A2, 36.7 in B2, etc.

My current code is

For j = 1 to nw
    For k = 1 to 4
       tWB.Sheets("Data").Cells(j, k) = A(j)
    Next k
Next j

This is my first time posting so i am unsure of the posting etique, so if more information is required I can try and provide it.

Here is the entire code

    Option Explicit
    Option Base 1
    Sub DataMerge()
    Dim FileNames As Variant, A() As Variant
    Dim i As Integer, nw As Integer, j As Integer, k As Integer
    Dim UserRange As Range, ImportRange As String
    Dim tWB As Workbook, aWB As Workbook
    Set tWB = ThisWorkbook
    FileNames = Application.GetOpenFilename(FileFilter:="Excel Filter(*.csv),*.csv", Title:="Open File(s)", MultiSelect:=True)
    Workbooks.Open FileNames(1)
    Set UserRange = Application.InputBox(Prompt:="Select Range: ", Title:="Import Range", Type:=8)
    ImportRange = UserRange.Address
    nw = UBound(FileNames)
    ReDim A(nw) As Variant
    For i = 1 To nw
        Workbooks.Open FileNames(i)
        Set aWB = ActiveWorkbook
        A(i) = aWB.Sheets(1).Range(ImportRange)
        aWB.Close SaveChanges:=False
    Next i

    tWB.Activate
    For j = 1 to nw
        For k = 1 to 4
           tWB.Sheets("Data").Cells(j, k) = A(j)
        Next k
    Next j
   End Sub

Upvotes: 3

Views: 923

Answers (1)

JNevill
JNevill

Reputation: 50034

Your code is VERY close. Instead:

For j = 1 to nw
    For k = 1 to 4
       tWB.Sheets("Data").Cells(j, k) = A(j)(k,1)
    Next k
Next j

Upvotes: 4

Related Questions