如何将数组返回到Excel VBA范围

温达尔芬

我一直在尝试从工作表中获取数据并将其放入数组中,然后将数组粘贴到其他工作表中。但是,循环后,我的数组返回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循环才能将Array粘贴到范围内吗?

显然,数组将在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
大卫·G

您的数组应该根据j整数进行填充,但是您不对其进行递增。

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
        Debug.Print (article_arr(j))
    End If
Next

同样,将数组粘贴到单个单元格时,它将完全按照您的描述进行操作。将第一个数组值粘贴到各处以获取数组的大小。要使其具有正确的值,您需要将其发送到与数组大小相同的范围内。例如,对于大小为2 x 3的数组,您将编写

Range("A1:B3") = array

在您的情况下,您希望大小是动态的,就像数组的大小一样。

k = 8
Range("A" & k & ":A" & k + Ubound(article_arr, 1)) = article_arr

应该做的把戏。如您所见,它将粘贴从A8开始并向下与数组中的值数相同长度的范围。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章