Грешка „Изисква се обект“ при препратка към динамично създадени контроли, съхранени в колекция, в класа на друга динамично създадена контрола

Използвам бутон за въртене, за да преминавам през датите на фаза. Когато извикам елемент от колекция, наречена customtextboxcollection, с неговата индексна стойност, получавам грешка „Изисква се обект“. Както бутонът за въртене, така и текстовото поле, чиято стойност се променя, са динамично създадени контроли, показвани в UserForm, наречен UserForm1.

Подчинението за създаване на елементите в колекцията customtextbox се изпълнява, преди да се щракне върху бутона за завъртане:

Dim customtextboxcollection As Collection
Dim spinbuttoncollection As Collection


Public Sub ComboBox1_Click() 'When a person is selected to enter hours for an employee from a combobox, it triggers the creation of the controls

Sheet1.Activate
CommandButton1.Enabled = True 'Enable the OK and Apply buttons when personnel title is selected.
UserForm1.Label2.Visible = True
UserForm1.ratebox.Visible = True
QuantityLabel.Visible = True
quantitybox.Visible = True

'The variables below are to access the table where I store saved information regarding the project phases I will add hours to.

Dim counter As Integer
counter = 6 'The index of the first row for phases
Dim phasecolumn As Integer
phasecolumn = 3 'The index of the column containing the phases
Dim checkboxnumber As Integer
checkboxnumber = 1 'This is the number needed to distinguish between the checkboxes that appear/disappear.
phasestartcolumn = 4
phaseendcolumn = 5
Dim customtextboxHandler As cCustomTextBoxHandler
Set customtextboxcollection = New Collection 'Sets the previously created collection

Dim spinbuttonHandler As cSpinButtonHandler 'This is my spin button handler class
Set spinbuttoncollection = New Collection 'Sets the previously created collection


'This Do-Loop locates a row on the table with saved information
Do
    If (Sheet3.Cells(savedpersonnelrow, savedpersonnelcolumn) = ComboBox1.Value) Then
        storagerow = savedpersonnelrow
        lastcomboboxvalue = ComboBox1.Value
        Exit Do
    End If

    savedpersonnelrow = savedpersonnelrow + 1

Loop Until (savedpersonnelrow = 82)

Sheet1.Activate

'These sections create the controls depending on the number of phases saved.

Set spin = UserForm1.Controls.Add("Forms.SpinButton.1")

        With spin
            .name = "SpinButton" & checkboxnumber
            .Left = 365
            .Top = topvalue + 6
            .Height = 15
            .Width = 40
            '.Value = Sheet3.Cells(storagerow, savedphasecolumn + checkboxnumber)
            'Sheet1.Activate


            Dim phasestart As Date
            phasestart = Sheet1.Cells(counter, phasestartcolumn).Value
            Dim phaseend As Date
            phaseend = Sheet1.Cells(counter, phaseendcolumn).Value

            spin.Min = phasestart
            spin.Max = phaseend
            spin.Orientation = fmOrientationVertical

            'Do

                '.AddItem Format(phasestart, "mmm-yy")
                'phasestart = DateAdd("m", 1, phasestart)

            'Loop Until (Month(phaseend) = Month(phasestart) And Year(phaseend) = Year(phasestart))

            Set spinbuttonHandler = New cSpinButtonHandler
            Set spinbuttonHandler.spin = spin
            spinbuttoncollection.Add spinbuttonHandler

        End With



Set ctext = UserForm1.Controls.Add("Forms.TextBox.1")

        With ctext
            .name = "CustomTextbox" & checkboxnumber
            .Left = 470
            .Top = topvalue + 6
            .Height = 15
            .Width = 40
            .Value = phasestart

            Set customtextboxHandler = New cCustomTextBoxHandler
            Set customtextboxHandler.ctext = ctext
            customtextboxcollection.Add customtextboxHandler

        End With

topvalue = topvalue + 15
counter = counter + 1
checkboxnumber = checkboxnumber + 1

Loop Until counter = 14

End Sub

В моя клас, наречен cSpinButtonHandler, препращам към този customtextboxcollection обект, свързан със съответния бутон за въртене:

Public WithEvents spin As MSForms.SpinButton


Private Sub spin_Click()

UserForm1.CommandButton3.Enabled = True


End Sub

Private Sub spin_SpinDown()

x = 0

Do
    x = x + 1

Loop Until spin.name = "SpinButton" & x

Dim spindate As Date
spindate = customtextboxcollection.Item(x).ctext.Value 'The error occurs here.

customtextboxcollection.Item(x).ctext.Value = DateAdd("m", -1, spindate)

End Sub

Защо тази справка генерира грешка? Кой е правилният начин за справка?


person VivaLaTexas    schedule 21.07.2014    source източник
comment
Вместо да използвате две отделни колекции и два различни класа, можете да създадете един клас, който да обработва всяка двойка контроли (едно завъртане и едно текстово поле). Това би било по-лесно за справяне по отношение на закачване на събития между всяка двойка.   -  person Tim Williams    schedule 21.07.2014
comment
Благодаря за отговора, Тим. Бихте ли посочили ресурс, който би могъл да ми помогне да навигирам в този процес? Промених и двете контроли на един и същи клас, но все още получавам същата грешка. Благодаря отново за отделеното време.   -  person VivaLaTexas    schedule 21.07.2014


Отговори (1)


Това не е отговор на истинския ви въпрос, а предложение за алтернативен подход, който може да е по-лесен за управление.

Вместо да използвате две отделни колекции и два различни класа, можете да създадете един клас, който да обработва всяка двойка контроли (едно завъртане и едно текстово поле). Това би било по-лесно за справяне по отношение на закачване на събития между всяка двойка.

clsSpinText:

Option Explicit

Public WithEvents txtbox As MSForms.TextBox
Public WithEvents spinbutn As MSForms.SpinButton


Private Sub spinbutn_Change()
    'here you can refer directly to "txtbox"
End Sub

Private Sub txtbox_Change()
    'here you can refer directly to "spinbutn"
End Sub

Когато добавяте вашите контроли, създайте по едно копие на clsSpinText на двойка и запазете тези екземпляри в една колекция.

person Tim Williams    schedule 21.07.2014