无法传递数组值

时间:2019-03-25 19:44:46

标签: arrays excel vba

我有一个子程序,用电子表格中固定范围内的用户定义值列表填充数组。我想从另一个调用此子,并利用数组中的值来驱动For Each循环。

调用子getInvoiceList时,我可以看到它确实用用户的值填充了数组invoiceList。但是它们不会传递回我打电话给的那个子。

Public Sub columnLoop()

    Dim i As Long, j As Long
    getInvoiceList
    Stop 'to view array values

    Sheets("Calculator").Columns(10).Font.Color = vbBlack

    For i = 0 To UBound(invoiceList)

    'Loops through column for specific value(as declared)
    'Recolors text when current cell value = specific value
        For j = 3 To Range("NumFilledRows").Value
            If Sheets("Calculator").Cells(j, 10).Value = invoiceList(i) Then
            Sheets("Calculator").Cells(j, 10).Font.Color = vbRed
        End If
    Next j
Next i

End Sub

'Fill array from fixed range
Public Sub getInvoiceList()
    Dim invoiceList() As Variant
    invoiceList = Sheet2.Range("C4:C14")

    Stop 'allows review of array.
End Sub

当我调用子“ getInvoiceList”时,可以看到它确实用用户的值填充了invoiceList数组。但是它们不会传递回我打电话给的那个子。

Run-time error '13': Type Mismatch      调试将我带到For i = 0 to UBound行。      “本地”窗口显示invoiceList,但在“停止”行和单击“调试”后都有value = empty

2 个答案:

答案 0 :(得分:1)

您可以将变量传入/传出sub。

Public Sub columnLoop()

    Dim i As Long, j As Long, InvoiceList As Variant
    getInvoiceList  InvoiceList
    Stop 'to view array values

    Sheets("Calculator").Columns(10).Font.Color = vbBlack

    For i = 0 To UBound(InvoiceList)

    'Loops through column for specific value(as declared)
    'Recolors text when current cell value = specific value
        For j = 3 To Range("NumFilledRows").Value
            If Sheets("Calculator").Cells(j, 10).Value = InvoiceList(i) Then
            Sheets("Calculator").Cells(j, 10).Font.Color = vbRed
        End If
    Next j
Next i

End Sub

'Fill array from fixed range
Public Sub getInvoiceList(ByRef InvoiceList As Variant)

    InvoiceList = Application.Transpose(Sheet2.Range("C4:C14").Value)

    Stop 'allows review of array.
End Sub

答案 1 :(得分:0)

使用集合可能会更容易。在下面尝试我的代码。

Public Sub columnLoop()
    Dim i As Long, j As Long
    Dim coll As New Collection

    'add items to collection
    For Each cell In Sheets(2).Range("C4:C14")
        coll.Add cell
    Next
    Stop 'to view array values

    Sheets("Calculator").Columns(10).Font.Color = vbBlack

    Dim itm As Variant

    For Each itm In coll
        'Loops through column for specific value(as declared)
        'Recolors text when current cell value = specific value
        For j = 3 To Range("NumFilledRows").Value
            If Sheets("Calculator").Cells(j, 10).Value = itm Then 'checks values against items in collection
                Sheets("Calculator").Cells(j, 10).Font.Color = vbRed
            End If
        Next j
    Next itm

End Sub