excelvba

Copying a String Array into a Range of cells (in MS Excel using VBA)


I can use a For construct to loop through the string array elements and copy their contents into the individual cells of the range; but is there a simpler way to directly copy the string array items into the Range?

The question Range to string array solves the exact opposite of what I am trying to do.


Updates:

Here is what I got till now:

' Create a header: Write a list of Fields from Array into Range
Dim strTest As String
Dim strArray() As String
Dim firstCellOftheTargetRange, lastCellOftheTargetRange  as String

strTest = "PERIOD,YEAR,SCENARIO,ANALYTICS,ENTITY,ACC_NUMBER,AMOUNT"
strArray = Split(strTest, ",")

firstCell = "A1" ' First Cell Of the Target Range
lastCell = convertNumberToColumnName(UBound(strArray) + 1) & "1" ' last Cell Of the Target Range 

Worksheets("SheetName").Range(firstCell & ":" & lastCell) = strArray

This code doesn't use WorksheetFunction.Transpose as it outputs row-wise. If you require the output to be column-wise use the function as shown by @mehow. Thanks


Solution

  • Like this

    Sub StringArrayToRange()
    
        Dim strArr(3) As String
        strArr(0) = "one"
        strArr(1) = "two"
        strArr(2) = "three"
    
        Range("A1:A" & UBound(strArr) + 1) = WorksheetFunction.Transpose(strArr)
    
    End Sub
    

    also, this for more examples and tutorial

    EDIT:
    this documentation explains why the WorksheetFunction.Transpose was used