【发布时间】:2016-07-25 12:49:57
【问题描述】:
我一直在尝试从工作表中获取数据并将其放入数组中,然后将数组粘贴到其他工作表中。但是,在循环之后,我的数组返回 Empty。我需要从 For 循环返回一些东西吗?我搜索了没有发现任何想法。
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。我在粘贴数组时也使用了错误的变量(新手错误)。它现在返回结果,但它只返回在粘贴范围内重复的数组的第一个值。我需要 for 循环将数组粘贴到范围吗?
显然数组将在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
【问题讨论】:
-
请提供一些数据和所需输出的示例,以便我们重现您的问题。请阅读How to create a Minimal, Complete, and Verifiable example的帮助主题
-
如果你设法使用了错误的变量,这意味着你没有在
Option Explicit中编码。在代码的最顶部写上Option Explicit,它会警告你这些事情。 -
@RonRosenfeld 感谢您的意见。我还将使用我们找到的解决方案编辑问题。
-
@DavidG 感谢您的意见,我对 VBA 很陌生,这很棒。