I have been trying to get data from a worksheet and put it into array and then paste the array to other worksheet. However, after the loop my array return Empty. Do I need to return something from the For Loop? I searched didn't find any idea.
Sub generate()
Dim article_arr() As Variant
Dim artCount As Integer
Dim filter As Integer
Dim RIL_itemCount As Integer
'Set PA number
filter = Sheet7.Range("B1").Value
RIL_itemCount = Sheet5.Cells(Sheet5.Rows.count, "A").End(xlUp).Row
'Count number article of PA selected
artCount = Application.WorksheetFunction.CountIf(Sheet5.Range("R:R"), filter)
'redim array
ReDim article_arr(0 To artCount)
Dim j As Integer
j = 0
'populate array with article number from Retail Item List
For i = 0 To RIL_itemCount
If (Sheet5.Cells(i + 2, 18).Value = filter) Then
article_arr(j) = Sheet5.Cells(i + 2, 1).Value
Debug.Print (article_arr(j))
End If
Next
'Paste Article number to range
Sheet7.Range("A8:A" & artCount) = articleArr()
End Sub
As mentioned by David G. I forgot to increment the J. I also use the wrong variable (newbie mistake) when pasting the Array. It now return result but it only return the first value of the array repeated over the pasted range. Do I need for loop to paste Array to range?
Apparently array will be pasted horizontally in the excel, which cause repetition of the first value when pasting the array to range. Adding WorksheetFunction.Transpose(array)
do the magic
Here is the updated code:
Sub generate()
Dim article_arr() As Variant
Dim artCount As Integer
Dim filter As Integer
Dim RIL_itemCount As Integer
'Set PA number
filter = Sheet7.Range("B1").Value
RIL_itemCount = Sheet5.Cells(Sheet5.Rows.count, "A").End(xlUp).Row
'Count number article of PA selected
artCount = Application.WorksheetFunction.CountIf(Sheet5.Range("R:R"), filter)
'redim array
ReDim article_arr(0 To artCount)
Dim j As Integer
j = 0
'populate array with article number from Retail Item List
For i = 0 To RIL_itemCount
If (Sheet5.Cells(i + 2, 18).Value = filter) Then
article_arr(j) = Sheet5.Cells(i + 2, 1).Value
j = j + 1
End If
Next
'Paste Article number to range
k = 8
Sheet7.Range("A" & k & ":A" & UBound(article_arr) + 7) = WorksheetFunction.Transpose(article_arr)
Debug.Print (article_arr(395))
End Sub