Excel VBA function returning an array

前端 未结 2 1539
礼貌的吻别
礼貌的吻别 2021-01-02 03:06

Can you create an Excel VBA function that returns an array in the same manner as LINEST does, for example? I would to create one that, given a supplier code, returns a list

2条回答
  •  清酒与你
    2021-01-02 03:44

    I think Collection might be what you are looking for.

    Example:

    Private Function getProducts(ByVal supplier As String) As Collection
        Dim getProducts_ As New Collection
    
        If supplier = "ACME" Then
            getProducts_.Add ("Anvil")
            getProducts_.Add ("Earthquake Pills")
            getProducts_.Add ("Dehydrated Boulders")
            getProducts_.Add ("Disintegrating Pistol")
        End If
    
        Set getProducts = getProducts_
        Set getProducts_ = Nothing
    End Function
    
    Private Sub fillProducts()
        Dim products As Collection
        Set products = getProducts("ACME")
        For i = 1 To products.Count
            Sheets(1).Cells(i, 1).Value = products(i)
        Next i
    End Sub
    

    Edit: Here is a pretty simple solution to the Problem: Populating a ComboBox for Products whenever the ComboBox for Suppliers changes it's value with as little vba as possible.

    Public Function getProducts(ByVal supplier As String) As Collection
        Dim getProducts_ As New Collection
        Dim numRows As Long
        Dim colProduct As Integer
        Dim colSupplier As Integer
        colProduct = 1
        colSupplier = 2
    
        numRows = Sheets(1).Cells(1, colProduct).CurrentRegion.Rows.Count
    
        For Each Row In Sheets(1).Range(Sheets(1).Cells(1, colProduct), Sheets(1).Cells(numRows, colSupplier)).Rows
            If supplier = Row.Cells(1, colSupplier) Then
                getProducts_.Add (Row.Cells(1, colProduct))
            End If
        Next Row
    
        Set getProducts = getProducts_
        Set getProducts_ = Nothing
    End Function
    
    Private Sub comboSupplier_Change()
        comboProducts.Clear
        For Each Product In getProducts(comboSupplier)
            comboProducts.AddItem (Product)
        Next Product
    End Sub
    

    Notes: I named the ComboBox for Suppliers comboSupplier and the one for Products comboProducts.

提交回复
热议问题