2014-02-05 6 views
1

Я пытаюсь использовать коллекцию для хранения только одной уникальной копии каждой строки, возвращаемой из запроса базы данных.Broken коллекции VB6. Недопустимый квалификатор

Когда я сталкиваюсь с новым. Я вижу, есть ли у меня это. Если я этого не сделаю, я добавлю его в свою коллекцию и в свой список. иначе я продолжаю разбор.

Когда я компилирую, я получаю эту ошибку (код в картинке тоже):

enter image description here

Что мне нужно изменить в моей коллекции?

+1

Почему вы не просто изменить SQL строки на «Выбрать Distinct FactorType»? –

ответ

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 вашего запроса и добавил другое условие where clause на FactorType Is NULL. Это приведет к тому, что база данных будет возвращать только те строки, которые вам нужны, поэтому нет необходимости писать код для фильтрации уникальных значений.

Вы также должны заметить, что этот код выполняется значительно быстрее. Если вы получаете всего около дюжины строк из своей базы данных (с исходным кодом), вы можете не заметить разницу, но с большим количеством строк разница в времени выполнения станет более очевидной.

0

Я думаю, вам нужно изменить объявление своей коллекции. Потому что таким образом вы объявили массив коллекций, и вы получили ошибку. Кроме того, я согласен с G Mastros, вы можете изменить инструкцию sql, и пусть сервер db сделает для вас работу. НТН

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 
1

Вы определили mostRecentList как массив коллекций и использовать его driectly.

Либо вы пишете:

Dim mostRecentList as Collection 

[...] 

Do While cnt < mostRecentList.count() 

или написать

Dim mostRecentList() as Collection 

[...] 

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

Кроме того, вам нужно создать экземпляр коллекции перед использованием ...

Смежные вопросы