Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA Only User-Defined Types error

Tags:

excel

vba

I have seen some discussion around this, but I am still puzzled by this error:

Only User-defined types defined in public object modules can be coerced to or from a variant or passed to late-bound functions

This is what I have (and it is also possible that the problem is with the failure to assign New LookupItem (see below)):

Public Type LookupItem
    Stock As String
    Price As String
End Type

Sub GetData()

    Dim PreviousPrices As Collection

    Dim MyStock As String
    Dim CurrentPrice As String
    Dim ALookupItem As LookupItem

    Set PreviousPrices = New Collection

    ' Assumption:  the first line of good data is #4
    MyRow = 4

    Dim Item As Variant
    ' Assumption:  Column 2 is the Stock Symbol; there are no blank lines until the end
    Do Until Trim$(Cells(MyRow, 2).Value) = ""
        ' Assumption:  Column 8 is the Sell Date, blank if not yet Sold
        If (Cells(MyRow, 8).Value = "") Then
            MyStock = Cells(MyRow, 2).Value
            CurrentPrice = ""
            For Each Item In PreviousPrices
                If Item.Stock = MyStock Then
                    CurrentPrice = Item.Price
                    Exit For
                End If
            Next Item

            If CurrentPrice = "" Then 'Go get it and put it in CurrentPrice
                ...
                ' Set ALookupItem = New LookupItem (if not commented, this returns invalid use of New keyword)
                ALookupItem.Stock = MyStock
                ALookupItem.Price = CurrentPrice
                PreviousPrices.Add ALookupItem
            End If

        End If
        MyRow = MyRow + 1
    Loop
End Sub

See what I've done wrong?

like image 425
Kelly Cline Avatar asked Dec 07 '25 06:12

Kelly Cline


1 Answers

As per my understanding (may be wrong), you cannot add a UDT into a collection (which is an object)

Therefore, you need to turn your UDT into a class. Then, instantiate an object and add it to the collection

like image 103
sam092 Avatar answered Dec 08 '25 20:12

sam092



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!