Private sub userform initialize ошибка как исправить

Option Explicit
Private Sub CommandButton1_Click()
Dim iLastRow As Long
    iLastRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
    Cells(iLastRow, 3) = Me.ComboBox3
    Cells(iLastRow, 5) = Me.TextBox1
    Cells(iLastRow, 2) = Me.TextBox2
    Cells(iLastRow, 6) = Me.TextBox3
    Cells(iLastRow, 7) = Me.TextBox4
    Cells(iLastRow, 4) = Me.ComboBox4
    Cells(iLastRow, 9) = Me.TextBox5
    Cells(iLastRow, 10) = Me.TextBox6
    Cells(iLastRow, 8) = Me.ComboBox1
    Cells(iLastRow, 12) = Me.ComboBox2
    Me.TextBox1 = ""
    Me.TextBox2 = ""
    Me.TextBox3 = ""
    Me.TextBox4 = ""
    Me.TextBox5 = ""
    Me.TextBox6 = ""
    MsgBox "Информация добавлена!", vbInformation, "База"
End Sub

[B]Private Sub UserForm_Initialize()
With Worksheets("Прайс-лист")
    Me.ComboBox1.List = .Range("A2:A" & .Cells(.Rows.Count, 1).End(xlUp).Row).Value
End With
With Worksheets("Сотрудники T")
    Me.ComboBox3.List = .Range("A2:A" & .Cells(.Rows.Count, 1).End(xlUp).Row).Value
End With
With Worksheets("Клиенты")
    Me.ComboBox4.List = .Range("C2:C" & .Cells(.Rows.Count, 1).End(xlUp).Row).Value
End With
With Worksheets("masterdata")
    Me.ComboBox2.RowSource = "=masterdata!" & .Range("B2:B" & .Cells(.Rows.Count, 2).End(xlUp).Row).Address
End With
End Sub[/B]

Private Sub ComboBox2_Change()
   If Me.ComboBox2.Value <> "" Then
       Me.ComboBox2.Value = Format(Me.ComboBox2, "dd/mmm/yyyy")
   End If
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
   Me.TextBox1 = Format(Me.TextBox1, "+7 ### ### ## ##")
End Sub

Private Sub CommandButton2_Click()
    End
End Sub

I am working with Excel 2016, and I am new to VBA. The userform initialize functionality was working, and then stopped. I am trying to figure out why.

I want to push a button on a worksheet, have a form pop up that accepts some input (text and a selection from a drop down list), and another button on the form to create another popup to accept more input (barcode scan or text entry) until it eventually exits based on a determined condition (run out of slots to populate with the scanned barcode) or the user exits.

I have the button on the worksheet. I have the userform. However, at some point, I had to rename userform_Initialize to <formName>_Initialize because I was getting errors about objects missing, and error 424. After doing so, the «compiler» is happy, but the initialize function is never called, so nothing is working on the userform.

I think what I am seeing is very similar to this other question, but I’m not sure, nor am I sure where to stick my code if I try to do that.

Am I taking the wrong approach?

Private Sub UserForm_Initialize() gives error 424 at runtime when I click on the commandButton to bring up the userform. Switching to Private Sub warehouseCheckinForm_Initialize(), the initialize function is never called when the userform populates, leaving the functionality on the form broken and causing other problems..

This is the code on the userform:

Public initialsInput As String
'*Initials of user scanning in stuff

Public modelSelected As String
'*Model selected for scanning

Public numItemsModel As Integer
'*Keep track of how many of the selected model are available to check in to the warehouse

Public searchBOMRange As Range
'*Range for search operations


Private Sub ModelComboBox_Change()
   modelSelected = ModelComboBox.Value
   numItemsModel = Application.WorksheetFunction.CountIf(searchBOMRange, modelSelected)
   numItemsModelLabel.Caption = numItemsModel

End Sub

Private Sub setInitialsButton_Click()

    If Len(InitialsTextBox.Value) = 2 Then
        initialsInput = InitialsTextBox.Value
    ElseIf Len(InitialsTextBox.Value) < 2 Then
        MsgBox "Enter in 2 letters for your initials"
    Else
        MsgBox "You entered in too much data!"
    End If

End Sub

Private Sub UserForm_Initialize()

    '*Start with empty inputs
    numItemsModel = 0
    searchBOMRange = Sheets("BOM").Range("C11:C2000")
    modelSelected = ""
    initialsInput = ""

    InitialsTextBox.Value = ""
    ModelComboBox.Clear
    numItemsModelLabel.Caption = numItemsModel

    '*Fill the Combo Boxes

    Dim oDictionary As Object
    Dim cellContentModel As String
    Dim rngComboValues As Range
    Dim rngCell As Range

    Set rngComboValues = Sheets("BOM").Range("C11:C2000")
        '*The first ~2000 items because there probably won't be BOMs bigger than that.  Test case was <1000
        '*Doing C:C took 5+ seconds to load the window
    Set oDictionary = CreateObject("Scripting.Dictionary")

    For Each rngCell In rngComboValues
        cellContentModel = rngCell.Value
        If Not oDictionary.exists(cellContentModel) Then
            oDictionary.Add cellContentModel, 0
        End If
    Next rngCell

    For Each itm In oDictionary.keys
        Me.ModelComboBox.AddItem itm
    Next itm

    Set oDictionary = Nothing




        'For Each cell In Sheets("BOM").Range("B:B")
    '    If cell.Value <> "" Then
    '        MakeComboBox.AddItem cell.Value
    '    End If
    'Next cell

End Sub



Private Sub warehouseScanButton_Click()

    For Each modelSelected In searchBOMRange

        If Len(initialsInput) < 2 Then
            Beep
            MsgBox "Enter your initials first!"
            End
        ElseIf Len(modelSelected) < 1 Then
            Beep
            MsgBox "Select a model first!"
            End
        ElseIf Len(initialsInput) >= 2 And Len(modelSelected) >= 1 Then
            scannedInput = InputBox("Scan a serial number, or type it in and mash the ENTER key")
            If scannedInput = "NA" Or scannedInput = "N/A" Then
                Beep
                MsgBox "You can't search for 'not applicable', it doesn't apply!"
                End
            End If
        End If

        '//Searches for empty serial number cell
        '// Model is in C, serial is in O (letter)
        '//offset is row, column; down is positive, right is positive

        Set matchedCell = modelSelected.Offset(0, 12)

        If matchedCell Is Nothing Then
            '//do stuff
            scannedInput = InputBox("Scan a serial number, or type it in and mash the ENTER key")

            matchedCell.Offset(0, 2).Value = initialsInput
            matchedCell.Offset(0, 3).Value = Now '// Checked in to Warehouse
            matchedCell.Offset(0, -2).Value = Now '// "Recv'd date"
            matchedCell.Offset(0, 1).Value = "W"

            numItemsModel = numItemsModel - 1


            'If Len(matchedCell.Offset(0, 4).Value) >= 2 And scannedInput <> "" Then
            '    Beep
            '    MsgBox "Serial Number " & scannedInput & " is already checked in to The Lab!"
            'ElseIf Len(matchedCell.Offset(0, 4).Value) < 2 Then
            '    matchedCell.Offset(0, 4).Value = initialsInput
            '    matchedCell.Offset(0, 5).Value = Now
            '    matchedCell.Offset(0, 1).Value = "L"
        End If

        If Not matchedCell Is Nothing Then '//If the cell has something in it
                '//Beep
                '//MsgBox "Error! This is unpossible!"
                '//End
            End If
        End If

    Next modelSelected

End Sub

This is the logic on the command button on the worksheet:

Private Sub WarehouseCheckinCommandButton_Click()
    '*Brings up the form
    WareHouseCheckinForm.Show

End Sub

I think somehow a keyword is involved, or something else. When I change the name of the function, I see some stuff at the top of the window changing. It goes from «Userform» to «General». I think that is important.

enter image description here

enter image description here

Edit 2

(Edit 1 was rolled in on the sly) Ok, so it sounds like I need to leave the initialize function as Userform_Initialize. This is what I get when I click on the command button run time error 91 object variable or With block variable not set and I have the option to debug. If I debug, I get this:

enter image description here

Selected Answer

Mussa

I think the error is that your loop does not match some ComboBox names in your UserForm1…

In the orange portion, you have a single ComboBox1 but the yellow portion has controls called ComboBox2, 6, 10  etc. and ComboBox3, 7, 11 etc. and so on but to ComboBox45

One problem is that that you final line:

'Me.Controls("ComboBox" & i + 44).List = .Offset(, i - 1).Value

(now commented out) can produce ComboBox names beyond ComboBox45 (which don’t exist — perhaps you deleted them).

Another problem is that after the row with ComboBox 22, the ComboBoxes were confused between columns wnet 29… rather than 26…). 

Finally your loop  For i=1 to 4…ought to read  2 to 5 (so beginning with ComboBox 2 and ending with 5+40= ComboBox45) as below, changes in bold:

Private Sub UserForm_Initialize()

With Sheets("BRANDS")
   With .Range("A2", .Cells(.Rows.Count, "A").End(xlUp))
        For i = 2 To 5
            Me.Controls("ComboBox" & i).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 4).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 8).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 12).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 16).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 20).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 24).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 28).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 32).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 36).List = .Offset(, i - 1).Value
            Me.Controls("ComboBox" & i + 40).List = .Offset(, i - 1).Value
            'Me.Controls("ComboBox" & i + 44).List = .Offset(, i - 1).Value
        Next
    End With
End With

End Sub

The revised code and corrected UserForm are in the attached sheet

Hope this fixes things for you.

Я пытаюсь сделать то, что написано на этом сайте http://www.excel-easy.com/vba/userform.html, но когда я нажимаю commandbutton (из элементов управления ActiveX) в рабочем листе, точно так же, как указано на веб-сайте, ничего не происходит. Я пытался использовать кнопку из элементов управления формы, но он говорит, что ошибка в этом —> DinnerPlannerUserForm.Show

Мой код:

Sub Button2_Click()
    DinnerPlannerUserForm.Show
End Sub

Когда я использовал F8, он сказал, что ошибка здесь -> Private Sub UserForm_Initialize()

Private Sub UserForm_Initialize()

    'Empty NameTextBox
    NameTextBox.Value = ""

    'Empty PhoneTextBox
    PhoneTextBox.Value = ""

    'Empty CityListBox
    CityListBox.Clear

    'Fill CityListBox
    With CityListBox
        .AddItem "San Francisco"
        .AddItem "Oakland"
        .AddItem "Richmond"
    End With

    'Empty DinnerComboBox
    DinnerComboBox.Clear

    'Fill DinnerComboBox
    With DinnerComboBox
        .AddItem "Italian"
        .AddItem "Chinese"
        .AddItem "Frites and Meat"
    End With

    'Uncheck DataCheckBoxes
    DateCheckBox1.Value = False
    DateCheckBox2.Value = False
    DateCheckBox3.Value = False

    'Set no car as default
    CarOptionButton2.Value = True

    'Empty MoneyTextBox
    MoneyTextBox.Value = ""

    'Set Focus on NameTextBox
    NameTextBox.SetFocus

End Sub

2015-07-11 00:44

7
ответов

Эта ошибка также может возникать, когда вы удаляете или удаляете текстовое поле из вашей формы, но не забудьте удалить его из строки при инициализации, например:

Private Sub UserForm_Initialize()
    CommandButton2.Enabled = False
    TextBox4.Enabled = False    'textbox deleted from form
End sub

2017-07-07 14:04

Я предполагаю, что эта проблема была решена, но для тех, кто только сейчас смотрит на это. У меня была эта проблема, и оказалось, что я удалил ComboBox из моей формы, но он все еще упоминается в коде. Как только я удалил этот раздел кода, он работал прекрасно.

2016-09-02 23:05

Я использовал тот же учебник и решил проблему, изменив команду Initialize:

Дается как

Private Sub UserForm_Initialize()

Я назвал свою форму пользователя (для моих собственных целей)

StdTimeCalculatorForm

и изменив код на

Private Sub StdTimeCalculatorForm_Initialize()

решил проблему. Надеюсь это поможет.

2018-02-23 17:31

У меня была такая же проблема. Я создавал одну и ту же форму в нескольких книгах и использовал одни и те же имена переменных. Я вставил в мой код для UserForm_Initialize. В коде все выглядело хорошо, но я вернулся и дважды проверил имена переменных в форме и понял, что забыл назвать два текстовых поля в моей форме. Мой код пытался присвоить значения txtMaxLines и txtAmount, но я не назвал их в форме, поэтому для vba было похоже, что они не существуют.

Я надеюсь, что это кому-то поможет, потому что, если у вас возникла та же проблема, что и у меня, то, когда он открывает редактор vba, он не переходит к строке с ошибкой и описание ошибки вообще не помогает.

2019-06-05 02:31

Трудно сказать, основываясь на том, что вы сказали. Но — тот факт, что вы сказали, используя F8, указывает на то, что ошибка в Private Sub UserForm_Initialize() предполагает, что пользовательская форма существует, и VBA знает, как ее найти (в противном случае событие инициализации не будет запущено при нажатии кнопки формы). Следовательно — это одна из строк в инициализирующем подпрограмме, которая является виновником. Какая строка специально помечена? Я предполагаю, что проблема заключается в простой опечатке имени одного из элементов управления (например, DinnerComboBox).

2015-07-11 02:53

Я смог решить их, изменив

Private Sub UserForm_Initialize()

в

Private Sub DinnerPlannerUserForm_Initialize()

Посмотрите, работает ли это

2016-09-05 07:51

Для меня это были проблемы с опечатками — я использовал то же руководство DinnerPlannerUserForm. Сработало, как только я проверил, что все поля (Имя) были точно такими же, как имена, указанные в коде.

Руководство хорошее, за исключением шага элемента «Показать пользовательскую форму», и, возможно, оно могло бы напомнить нам дважды проверить правильность имен. Я впервые использовал это руководство около 6 лет назад, и за эти годы оно помогло мне создать несколько невероятно полезных форм.


Al Blair

10 фев ’22 в 10:15
2022-02-10 10:15

2022-02-10 10:15

Студворк — интернет-сервис помощи студентам

сабж есть форма с названием Userform1
есть модуль Frm1
в нем процедура

Visual Basic
1
2
3
Sub Frm1_show()
UserForm1.Show
End Sub

на листе кнопка к которой привязан макрос Frm1_show.

Раньше форма открывалась, теперь при нажатии кнопки уходит в дебаггер с сообщением, мол object required.
сломалось после значительного кодинга, но совершенно не этой части, даже и не трогала форму, через макросы проверяла работоспособность.
Из общих изменений на этот этапе были переименование некоторых модулей и процедур, но это я все проверила и выправила.
Ошибка идет именно внутри процедуры на строчке UserForm1.Show.
имя формы точно такое, выбирается из списка подстановки.

Что не так? может к форме обратиться как-то по взрослому, через application или еще как, знаю некоторые функции листа не работают пока весь путь иерархии объектов не пропишешь.

Помогите плиз

Добавлено через 5 часов 38 минут
Проблема решена.
Оказалось на событии инициализации формы стоял такой код:

Visual Basic
1
2
3
Private Sub UserForm_Initialize()
    Call Frm.Frm1_Init
End Sub

Как уже писала, накануне переименовывала модули, и обращение к функциям прописывала в формате

Visual Basic
1
имя_модуля.имя_процедуры

тут при вставке префикса в виде имени модуля закралась опечатка (модуль назван Frm1). Бедняга Excel пытался найти метод неописанного класса.
Исправление имени модуля в обращении — все исправило.

Visual Basic
1
2
3
Private Sub UserForm_Initialize()
    Call Frm1.Frm1_Init
End Sub

Понравилась статья? Поделить с друзьями:
  • Как найти периметр прямоугольника прямо
  • Звуковой анализ слова схема слова 1 класс как ее составить
  • Мужская стрижка как исправить
  • Как найти сумму длин всех отрезков
  • Как найти объем фосгена