Meesha
Meesha

Reputation: 821

Filling a String in to different cells

I want to fill a series of cells with a Array but I am unable to do it.

1)

Dim Principal() As String
Dim txt As String

For i = LBound(Principal) To UBound(Principal)
    txt = txt & Principal(i)  & vbCrLf
Next i
MsgBox txt

2)

Dim Principal() As String
Dim txt As String

For i = LBound(Principal) To UBound(Principal)
    Worksheets("Sheet1").Cells(i, 3) = Principal(i)
Next i

I can see the output in the first example i.e MsgBox but I get an error when I try to store in to different cells. Thanks in advance.

Upvotes: 1

Views: 53

Answers (1)

L42
L42

Reputation: 19737

Alex and Sorceri already pointed out that by default, arrays start at index 0.
But aside from that, you don't need to loop to pass your array to range.

' 1D Array
With Worksheets("Sheet1")
    .Range("C1:C" & Ubound(Principal) + 1) = Application.Transpose(Principal)
End With

Take note of the + 1. If Option Base = 1 then you'll have to remove it.
Also take note that if you're passing 1D array to range, you'll need to Transpose the array.

Upvotes: 3

Related Questions