Userform1 show ошибка

I created an ActiveX button to open a form using the line

UserForm1.Show 

but when I click the button I get error 9 (subscript out of range). The form exists and the name of the form is UserForm1. When I debug, it highlights the line UserForm1.Show but I cannot figure out what is wrong.

Edit:

The initialize code is below

Private Sub UserForm_Initialize()
Let list1 = Array()
For j = 0 To 67
list1(j) = Sheet2.Cells(2+j, 1)
Next
Let colors = Array("Blue", "Black", "Gold", "Green")
ComboBox1.List = list1
ListBox1.List = colors
End Sub

Ben Rhys-Lewis's user avatar

asked Mar 21, 2016 at 21:06

Colleen's user avatar

8

You’ve not properly declared your list1 variable.

ALWAYS declare all of your variables, and in the case of arrays, when possible to dimension at initialization, do so. Or, leave them as variant and you can assign using the Array(...) function (like you do with colors). But for list1 array, you’ve initialized it as an empty array with an upper-bound of -1, so the very first assignment to list1(0) will fail, as 0 is out of bounds. Instead, since you know this array needs to have len = 68, just dimension it that way with the Dim statement:

Option Explicit  ' # Enforce variable declaration!!
Private Sub UserForm_Initialize()
Dim list1(67) 
Dim colors() 
Dim j as Long

colors = Array("Blue", "Black", "Gold", "Green")

For j = 0 to 67
    list1(j) = ...

(If you need to resize later, you can use ReDim and ReDim Preserve statements).

answered Mar 22, 2016 at 15:12

David Zemens's user avatar

David ZemensDavid Zemens

52.9k11 gold badges80 silver badges129 bronze badges

0

So I know this is an old post but I started working on a project and I came across this after encountering the same problem.

What I needed was code to fill a ListBox when the userform initialized and at first, I tried using arrays and collections to do it which gave error (9) and brought me here. Then I just took the array out and added the data straight into the ListBox. You could do this with a ComboBox as well. See below. David Zemens answer works but you can’t resize an already dimensioned array so you have to make the array bigger then what you could use wich just adds empty spaces to the ListBox.

Option Explicit

Private Sub UserForm_Initialize() 'Get headers for List Box
Dim colCount As Integer
Dim i As Integer

colCount = Cells(1, Columns.Count).End(xlToLeft).Column 'How many headers to work with

For i = 1 To colCount
 lBox_headers.AddItem Cells(1, i) 'Add headers to this listbox
Next i

End Sub

This code is just grabbing column headers and adding them to a list box. Hope it helps someone else who finds themselves here.

answered Jul 12, 2020 at 20:38

Ken Brue's user avatar

Poceslav

0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

1

Excel

28.05.2020, 13:31. Показов 2551. Ответов 14

Метки vba excel (Все метки)


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

Я создал кнопку ActiveX, чтобы открыть форму, используя строку
UserForm1.Show
но когда я нажимаю кнопку, я получаю ошибку 9 (индекс вне диапазона). Форма существует, и имя формы — UserForm1. Когда я отлаживаю, он выделяет строку UserForm1.Show, но я не могу понять, что не так.

Visual Basic
1
2
3
4
Private Sub CommandButton1_Click()
Sheets("Лист1").Activate
UserForm1.Show
End Sub

Как исправить?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

28.05.2020, 13:31

Ответы с готовыми решениями:

Ошибка при открытии файла — Ошибка в части содержимого в книге
Добрый день!

Открываю файл. Создаю макросом сводную таблицу, сохраняю файл.
Затем при попытке…

Ошибка method range of object global failed в чем ошибка
Sub ПроверкаВвода()

Dim A As Range
Dim B As Range …

Ошибка 48 — ошибка при загрузке DLL
Здравствуйте, ранее на этом отрезке кода всё было гладко
Dim WordApp As Word.Application
‘создаём…

Ошибка run time error 6 overflow, что не так? (без cost.Text = c6 вроде сначала робил, а потом удалял и всё равно ошибка
Dim h, w, l, wr, lr, p, a As String

Private Sub CommandButton1_Click()

h = InputBox("Введите…

14

141 / 124 / 50

Регистрация: 10.11.2011

Сообщений: 620

28.05.2020, 13:49

2

Цитата
Сообщение от Poceslav
Посмотреть сообщение

я нажимаю кнопку, я получаю ошибку 9 (индекс вне диапазона)

покажите на примере.



0



0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

28.05.2020, 14:07

 [ТС]

3

Ошибка 9

Ошибка 9

Вот



0



0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

28.05.2020, 14:09

 [ТС]

4



0



1837 / 1153 / 353

Регистрация: 11.07.2014

Сообщений: 4,072

28.05.2020, 14:25

5

Poceslav, смотреть надо не на эту строчку, а на код при загрузке формы, в инициализации, если есть и проч

Добавлено через 11 минут
У вас в коде формы под комбат1 есть строка If L = 1 Then, а End If отсутствует. Исправляйте ошибки



1



2658 / 1657 / 754

Регистрация: 23.03.2015

Сообщений: 5,210

28.05.2020, 14:34

6

Poceslav,
Исправлено…



1



Narimanych

2658 / 1657 / 754

Регистрация: 23.03.2015

Сообщений: 5,210

28.05.2020, 14:37

7

Уберите везде

Visual Basic
1
Sheets("Лист 1").Select

Он у вас и так в данный момент активный…



1



1837 / 1153 / 353

Регистрация: 11.07.2014

Сообщений: 4,072

28.05.2020, 14:51

8

Poceslav, а что вы не изменили то, что я писал, у вас же просто ошибка катит в Private Sub CommandButton1_Click()



0



0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

28.05.2020, 17:18

 [ТС]

9

Narimanych, Странно все равно не работает
primer.zip



0



2658 / 1657 / 754

Регистрация: 23.03.2015

Сообщений: 5,210

28.05.2020, 17:36

10

Poceslav,
Что не работает?



0



0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

28.05.2020, 17:39

 [ТС]

11

Narimanych, Ошибка 9
Хотя я вроде удалил все ненужные выборы 1 листа



0



2658 / 1657 / 754

Регистрация: 23.03.2015

Сообщений: 5,210

28.05.2020, 17:40

12

Цитата
Сообщение от Poceslav
Посмотреть сообщение

оде удалил все ненужные выборы 1 листа

Посмотите файл, что вы мне прислали…



1



0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

28.05.2020, 17:44

 [ТС]

13

Narimanych,
Все разобрался
У меня Лист 1 вместо Лист1 было написано
Спасибо за потраченное время



0



2658 / 1657 / 754

Регистрация: 23.03.2015

Сообщений: 5,210

28.05.2020, 17:55

14

Лучший ответ Сообщение было отмечено Poceslav как решение

Решение

Poceslav,
Посмотрел — У вас там жуть…
Кто-то ,

ну а может быть никто

дал вам неполный код….( а может вы его сами… того…)
1) вызываются процедуры, которых у вас в коде нет…
2) опять же кто-то в названия листов ввел пробел-(заметил не я — Pashulka, за что ему отдельное спасибо )
обратите внимание- в коде «Лист 1» и «Лист 2» а у вас в файле они «Лист1» и «Лист2»
3) Ну и по стилю видно, что над сим кодом рукоблудствовал не один человек…

Что в конечном итоге привело к получению результата , аналогичного письму дяди Федора папе и маме («Каникулы в Простоквашино»

Вывод — надо писать начисто, но я пас…



1



0 / 0 / 0

Регистрация: 17.05.2020

Сообщений: 12

28.05.2020, 18:22

 [ТС]

15

Narimanych, Этот код мне дали в пример
И в этот пример я должен был просто подставить свои значения
Но видно не судьба



0



  • #1

I have a userform, UserForm1.

In a module, I have the code:

Code:

Sub testform()
UserForm1.Show
End Sub

When I initially ran the testform sub, the userform shows which is fine.

However, the moment I make some changes to the userform (e.g. I added labels, textboxes, etc), I can not run the test form sub. I keep getting debug error and it points to the

And when I click on reset button, it takes me to the userform1 — but al the changes I made were discarded althuogh I saved those changes before I ran the testform sub.

Why is this happening and what do I need to do save my changes and enable the sub to run?

Thanks

 

Leo

Пользователь

Сообщений: 115
Регистрация: 01.01.1970

На время выполнения макроса вывожу на экран простенькую UserForm в модальном режиме с текстом типа «Подождите, работаю..»  
Для вывода формы на экран в начале макроса использую UserForm1.Show (0), в конце макроса использую UserForm1.Hide  
В свойствах UserForm1, в ShowModal стоит значение True.  
В простеньком примере все работает безукоризненно.  
Но когда вставляю эту же UserForm с этими же командами в свои готовые макросы, то UserForm появляется в виде рамки с чистым полем внутри, без надписи. Причем в одних макросах поле Caption активное (синий цвет), а в других – не активное (серый).  

  Кто-нибудь знает, в чем может быть дело?

 

Когда делал свой прогресс-бар, сталкивался с подобным.  

  Добавляйте в код строки  
DoEvents  
и  
UserForm1.Repaint  

  до тех пор, пока не заработает всё как надо :)  

  Посмотрите пример здесь:

http://www.programmersforum.ru/showthread.php?t=28112

 

LEO037

Пользователь

Сообщений: 32
Регистрация: 01.01.1970

Виноват, в первом сообщении имелся в виду немодальный режим, чтобы макрос продолжал работать.  

  EducatedFool,    
Ваш совет помог. Когда после UserForm1.Show (0) добавил UserForm1.Repaint, то этого оказалось достаточно, чтобы текст появился (правда, Titlebar остается не активным). А добавление DoEvents ничего не меняет.  
Так или иначе, текст выводится.  
Спасибо!

 

Мне помогла задержка в 1 секунду перед выполнением макроса.  

  —————-  
Application.Wait Time:=Now + TimeValue(«0:00:01»)  
‘дальше Ваш код  
—————-

 

LEO037

Пользователь

Сообщений: 32
Регистрация: 01.01.1970

Спасибо, Дъмитръ, но увы — у меня этот способ не сработал:( (кроме честной задержки на 1 секунду:)))  
Мне иногда помогало отключить и заново включить надстройку Analysis ToolPak — VBA, но сейчас не сработало.    
Никак не пойму, почему в одном макросе все нормально работает, а в другом глючит…

 

Leo037, так Вы задержку поставьте в инициализации или активации Вашей формы или в «Private Sub …()» формы ;)

 

LEO037

Пользователь

Сообщений: 32
Регистрация: 01.01.1970

Я в модуле, в тексте макроса ставлю сначала UserForm.Show (0), Wait1.Repaint, а в конце — UserForm1.Hide. Там же, в начале макроса, и добавлял Application.Wait Time:=Now + TimeValue(«0:00:01»)  
В коде UserForm, где Private Sub UserForm_Click(), у меня ничего не прописано.  
Я что-то неверно делаю?

 

> Причем в одних макросах поле Caption активное (синий цвет), а в других – не активное (серый)  

  Вы, наверное, в своих макросах используете методы SELECT или ACTIVATE  
Когда научитесь избавляться в коде от этих нехороших слов — тогда и запущенная форма будет постоянно активной (с синей полоской заголовка)  

  Можете внутри макроса добавить несколько строк UserForm.Show 0  
Тогда полоска всегда будет синей (эта строка активирует форму)

 

И вообще, покажите код своего макроса.  

  Вместо того, чтобы мудрить с прогрессбаром, проще оптимизировать макрос, чтобы тот выполнялся за доли секунды — тогда и форма не нужна будет.

 

LEO037

Пользователь

Сообщений: 32
Регистрация: 01.01.1970

#10

06.08.2010 13:29:59

EducatedFool, действительно, у меня там Activate и Select достаточно понатыкано. Но как избавиться от этих нехороших слов? Мне надо обработать данные (в том числе и отсортировать) на двух разных листах.  
Сильно повысить скорость макроса вряд ли возможно — я отключаю обновление экрана и автопересчет, но когда приходится обрабатывать несколько тысяч строк, то время работы макроса уже существенное.  
Впрочем, вод код, макрос на кнопке Этап 1.

Прикрепленные файлы

  • post_143493.rar (85.4 КБ)

INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Eng-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

UserForm1.Show gives an error…

UserForm1.Show gives an error…

(OP)

28 Aug 01 16:39

Okay, here’s the setup: I’ve got an .XLS file storing a set of macros (modules) and a single userform (called UserForm1). Now, I’m invoking the macros from another worksheet that I opened in Excel and I’m trying to load the userform that I created:

Sub ShowMyForm()
    UserForm1.Show    
End Sub

but everytime I try, I get the same error:

Run-time error ‘424’
   Object Required

Can someone help me out here? I’m getting annoied with this thing.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Resources

Low-Volume Rapid Injection Molding With 3D Printed Molds

Learn methods and guidelines for using stereolithography (SLA) 3D printed molds in the injection molding process to lower costs and lead time. Discover how this hybrid manufacturing process enables on-demand mold fabrication to quickly produce small batches of thermoplastic parts. Download Now

Design for Additive Manufacturing (DfAM)

Examine how the principles of DfAM upend many of the long-standing rules around manufacturability — allowing engineers and designers to place a part’s function at the center of their design considerations. Download Now

Industry Perspective: Education and Metal 3D Printing

Metal 3D printing has rapidly emerged as a key technology in modern design and manufacturing, so it’s critical educational institutions include it in their curricula to avoid leaving students at a disadvantage as they enter the workforce. Download Now

Taking Control of Engineering Documents

This ebook covers tips for creating and managing workflows, security best practices and protection of intellectual property, Cloud vs. on-premise software solutions, CAD file management, compliance, and more. Download Now

Join Eng-Tips® Today!

Join your peers on the Internet’s largest technical engineering professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Eng-Tips Forums:

  • Eng-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Понравилась статья? Поделить с друзьями:
  • User32 dll ошибка windows 10
  • User profile service ошибка 1534
  • User not found ошибка user not found
  • Use trace for backtrace ошибка koala
  • Use case ошибки