我一直試圖從工作表中獲取數據並將其放入數組,然後將該數組粘貼到其他工作表。但是,循環後我的數組返回空。我是否需要從For循環返回一些內容?我搜查沒有發現任何想法。如何將數組返回到範圍excel vba
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
正如由David G.提到忘了遞增J.粘貼陣列時我也使用了錯誤的變量(新手錯誤)。它現在返回結果,但它只返回在粘貼範圍內重複的數組的第一個值。我需要循環將數組粘貼到範圍嗎?
顯然數組將被粘貼在excel中水平,當數組粘貼到範圍時會導致重複第一個值。添加WorksheetFunction.Transpose(array)
做魔術
這裏是更新的代碼:
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
請提供一些數據和所需輸出的示例,以便我們可以重現您的問題。請閱讀[如何創建最小,完整和可驗證示例]的幫助主題(http://stackoverflow.com/help/mcve) –
如果設法使用了錯誤的變量,這意味着您沒有編碼'Option Explicit'。在你的代碼最上面寫上'Option Explicit',它會警告你這些事情。 –
@RonRosenfeld感謝您的意見。我還將用我們找到的解決方案編輯問題。 – Windalfin