Excel VBA仅用户定义类型错误

时间:2014-01-03 02:48:43

标签: excel-vba vba excel

我已经看到了一些关于此的讨论,但我仍然对这个错误感到困惑:

  

只能在公共对象模块中定义用户定义的类型   被强制转换为变体或传递给后期函数

这就是我所拥有的(问题还在于未能分配New LookupItem(见下文)):

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

看看我做错了什么?

2 个答案:

答案 0 :(得分:3)

根据我的理解(可能是错误的),你不能将UDT添加到集合中(这是一个对象)

因此,您需要将UDT转换为类。然后,实例化一个对象并将其添加到集合

答案 1 :(得分:1)

我认为VBA集合只能存储本机变量或对象。

我总是用所需的成员创建类(后来我很高兴,因为我最终还添加了一些方法)。