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
asked Mar 21, 2016 at 21:06
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 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
Poceslav 0 / 0 / 0 Регистрация: 17.05.2020 Сообщений: 12 |
||||
1 |
||||
Excel 28.05.2020, 13:31. Показов 2551. Ответов 14 Метки vba excel (Все метки)
Я создал кнопку ActiveX, чтобы открыть форму, используя строку
Как исправить?
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
28.05.2020, 13:31 |
Ответы с готовыми решениями: Ошибка при открытии файла — Ошибка в части содержимого в книге Открываю файл. Создаю макросом сводную таблицу, сохраняю файл. Ошибка method range of object global failed в чем ошибка Dim A As Range Ошибка 48 — ошибка при загрузке DLL Ошибка run time error 6 overflow, что не так? (без cost.Text = c6 вроде сначала робил, а потом удалял и всё равно ошибка Private Sub CommandButton1_Click() h = InputBox("Введите… 14 |
141 / 124 / 50 Регистрация: 10.11.2011 Сообщений: 620 |
|
28.05.2020, 13:49 |
2 |
я нажимаю кнопку, я получаю ошибку 9 (индекс вне диапазона) покажите на примере.
0 |
0 / 0 / 0 Регистрация: 17.05.2020 Сообщений: 12 |
|
28.05.2020, 14:07 [ТС] |
3 |
Вот
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 |
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 |
|||
Уберите везде
Он у вас и так в данный момент активный…
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, Странно все равно не работает
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
0 |
2658 / 1657 / 754 Регистрация: 23.03.2015 Сообщений: 5,210 |
|
28.05.2020, 17:40 |
12 |
оде удалил все ненужные выборы 1 листа Посмотите файл, что вы мне прислали…
1 |
0 / 0 / 0 Регистрация: 17.05.2020 Сообщений: 12 |
|
28.05.2020, 17:44 [ТС] |
13 |
Narimanych,
0 |
2658 / 1657 / 754 Регистрация: 23.03.2015 Сообщений: 5,210 |
|
28.05.2020, 17:55 |
14 |
Сообщение было отмечено Poceslav как решение РешениеPoceslav,
дал вам неполный код….( а может вы его сами… того…) Что в конечном итоге привело к получению результата , аналогичного письму дяди Федора папе и маме («Каникулы в Простоквашино» Вывод — надо писать начисто, но я пас…
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 |
На время выполнения макроса вывожу на экран простенькую UserForm в модальном режиме с текстом типа «Подождите, работаю..» Кто-нибудь знает, в чем может быть дело? |
Когда делал свой прогресс-бар, сталкивался с подобным. Добавляйте в код строки до тех пор, пока не заработает всё как надо Посмотрите пример здесь: http://www.programmersforum.ru/showthread.php?t=28112 |
|
LEO037 Пользователь Сообщений: 32 |
Виноват, в первом сообщении имелся в виду немодальный режим, чтобы макрос продолжал работать. EducatedFool, |
Мне помогла задержка в 1 секунду перед выполнением макроса. —————- |
|
LEO037 Пользователь Сообщений: 32 |
Спасибо, Дъмитръ, но увы — у меня этот способ не сработал:( (кроме честной задержки на 1 секунду:))) |
Leo037, так Вы задержку поставьте в инициализации или активации Вашей формы или в «Private Sub …()» формы |
|
LEO037 Пользователь Сообщений: 32 |
Я в модуле, в тексте макроса ставлю сначала UserForm.Show (0), Wait1.Repaint, а в конце — UserForm1.Hide. Там же, в начале макроса, и добавлял Application.Wait Time:=Now + TimeValue(«0:00:01») |
> Причем в одних макросах поле Caption активное (синий цвет), а в других – не активное (серый) Вы, наверное, в своих макросах используете методы SELECT или ACTIVATE Можете внутри макроса добавить несколько строк UserForm.Show 0 |
|
И вообще, покажите код своего макроса. Вместо того, чтобы мудрить с прогрессбаром, проще оптимизировать макрос, чтобы тот выполнялся за доли секунды — тогда и форма не нужна будет. |
|
LEO037 Пользователь Сообщений: 32 |
#10 06.08.2010 13:29:59 EducatedFool, действительно, у меня там Activate и Select достаточно понатыкано. Но как избавиться от этих нехороших слов? Мне надо обработать данные (в том числе и отсортировать) на двух разных листах. Прикрепленные файлы
|
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: Run-time error ‘424’ Can someone help me out here? I’m getting annoied with this thing. Red Flag SubmittedThank you for helping keep Eng-Tips Forums free from inappropriate posts. |
ResourcesLearn 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 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 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 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:
- Talk 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