Excel VBA Only User-Defined Types error

落花浮王杯 提交于 2020-06-26 04:28:08

问题


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?


回答1:


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




回答2:


I think that VBA collections can only store native variables or objects.

I always create classes with the required members (and later I'm happy about it because I end up for adding a few methods as well).



来源:https://stackoverflow.com/questions/20895688/excel-vba-only-user-defined-types-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!