1

我试图使用一个集合来存储从数据库查询返回的每个字符串的唯一副本。

当我遇到一个新的。我看看我是否已经拥有它。如果我不这样做,我会将其添加到我的收藏和组合框中。否则我继续解析。

当我编译时,我得到这个错误(图片中的代码也是):

在此处输入图像描述

我需要对我的收藏进行哪些更改?

4

3 回答 3

3

我建议你试试这个。

Sub FillEstimatesRoofLaborTypeCombo()
    Dim rstEstimateFactorTypes As Recordset
    Dim Sqlstring As String

    Sqlstring = "Select Distinct FactorType " + _
                "From EstimateFactors " + _
                "Where Component = 'Roof' And ComponentPart = 'Labor' And FactorType Is Not NULL"

    Set rstEstimateFactorTypes = cnnSel.OpenRecordset(Sqlstring, dbOpenSnapshot)

    With rtsEstimateFactorTypes
        Do While Not .EOF
            frmEstimates.cboRoofLaborType.AddItem .Fields!FactorType
            .MoveNext
        Loop
    End With
End Sub

您会注意到代码的编码要简单得多。我在查询的 select 子句中添加了一个 distinct,并在 FactorType Is Not NULL 上添加了另一个 where 子句条件。这将导致数据库只返回您想要的行,因此无需编写代码来过滤掉唯一值。

您还应该注意到此代码的执行速度要快得多。如果您只从数据库(使用您的原始代码)中获得十几行,您可能不会注意到差异,但是如果行越多,执行时间的差异就会变得更加明显。

于 2014-02-05T18:52:13.573 回答
1

您已将 mostRecentList 定义为集合数组并直接使用它。

要么你写:

Dim mostRecentList as Collection

[...]

Do While cnt < mostRecentList.count()

或者你写

Dim mostRecentList() as Collection

[...]

Do While cnt < mostRecentList(lindex).count()

此外,您需要在使用前实例化您的收藏......

于 2014-02-06T17:45:44.917 回答
0

我认为您需要更改收藏的声明。因为这样你声明了集合数组,所以你得到了错误。除此之外,我同意 G Mastros 的观点,您可以更改 sql 语句,让数据库服务器为您完成工作。高温高压

Sub FillEstimatesRoofLaborTypeCombo()
    ' this declares not a collection but a dynamic array of collections
    Dim mostRecentList() As Collection

    Debug.Print TypeName(mostRecentList)
    Debug.Print IsArray(mostRecentList)

    ' before using dynamic array ReDim must be used to alocate space in array
    ReDim mostRecentList(10)

    ' now mostRecentList has 10 elements each element is a collection
    ' before using any of this collection an new instance must be created
    Set mostRecentList(LBound(mostRecentList)) = New Collection

    ' now the first array element contains initialised instance of a collection
    ' and it is possible to add items to that collection
    mostRecentList(LBound(mostRecentList)).Add Item:="item_1", Key:="key_1"
    Debug.Print mostRecentList(LBound(mostRecentList)).Count

    ' *************************************************************************
    ' what you wanted was probably to have one collection instance like this
    ' declare without parenthesis
    Dim mostRecentListCol As Collection
    Set mostRecentListCol = New Collection

    Debug.Print TypeName(mostRecentListCol)
    Debug.Print IsArray(mostRecentListCol)
    Debug.Print mostRecentListCol.Count

End Sub

输出:

Object()
True
 1 
Collection
False
 0 
于 2014-02-06T05:25:38.477 回答