Vba excel формула массива

 

IgorBoot

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

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

#1

13.11.2018 22:39:22

Добрый вечер Уважаемые Эксперты.

К своему большому стыду не смог самостоятельно разобраться, с тем как с помощью VBA выносить на лист, в диапазон ячеек т.н. формулы массива.
Это даже несмотря на то, что на этом и аналагичных ресурсах подобная проблематика поднималась и показывались некоторые решения.
Итак, у нас имеются три столбца:
— Первый столбец содержит номер текущей строки.
— Второй столбец содержит последовательный набор чисел от 1 до 4, с повторениями, будем считать что это номер участка
— Третий столбец содержит некоторый произвольный набор чисел.
Помимо этого у нас имеется вспомогательная ячейка
— Cells(4, 5) — вспомогательный максимум для столбца с текущими строками
И два столбца для поиска максимума по условию, один на листе, другой на VBA
— Четвертый столбец — Максимум по условию написанные на листе
— Пятый столбец — Максимум по условию написанные с помощью VBA
Формула для  максимума на листе выглядит следующим образом:

Код
{=МАКС(ЕСЛИ(ДВССЫЛ("R10C[-5]:R"&R4C5&"C[-5]";ЛОЖЬ)=RC[-1];ДВССЫЛ("R10C[-4]:R"&R4C5&"C[-4]";ЛОЖЬ)))}

Данная формула на листе работает, к ней притензий нет.
И формула максимума с помощью VBA:

Код
Range(Cells(13, 8), Cells(16, 8)).FormulaArray = "=MAX(IF(INDIRECT(""R10C[-5]:R""&R4C5&""C[-5]"";FALSE)=RC[-1];INDIRECT(""R10C[-4]:R""&R4C5&""C[-4]"";FALSE)))"

При компиляции программы на этой строке выдается ошибка 1004.
Причины мне к сожалению не ясны. И если быть предельно честным, мне не удалось даже значительно более простую формулу массива поместить просто в ячейку используя VBA.

Прошу помочь разобраться.

Благодарю.

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

  • Вопрос_по_Формуле_Массива.xlsm (15.17 КБ)

Изменено: IgorBoot13.11.2018 22:41:37

 

БМВ

Модератор

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

Excel 2013, 2016

#2

13.11.2018 23:11:23

разделитель ; в коде заменит на , и вставлять в одну ячейку, после протянуть или копи пэст на нужный диапазон.

Код
Cells(13, 7).FormulaArray = "=MAX(IF(INDIRECT(""R10C[-5]:R""&R4C5&""C[-5]"",FALSE)=RC[-1],INDIRECT(""R10C[-4]:R""&R4C5&""C[-4]"",FALSE)))"

Изменено: БМВ13.11.2018 23:14:28

По вопросам из тем форума, личку не читаю.

 

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

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

БМВ

Модератор

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

Excel 2013, 2016

Изменено: БМВ13.11.2018 23:27:30

По вопросам из тем форума, личку не читаю.

 

IgorBoot

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

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

#5

13.11.2018 23:23:56

Уважаемый

БМВ

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

БМВ

, позвольте  уточнить

Цитата
вставлять в одну ячейку, после протянуть или копи пэст на нужный диапазон.

почему нельзя сразу на весь диапазон задавать? я уже попробовал и у меня к сожаленею не получилось. Везде выдается одно и тоже значение.
Если идти по сценарию «Copy—>Paste», то получается в диапазоне будет опять использоваться .FormulaArray?

Благодарю за Ответ.

 

БМВ

Модератор

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

Excel 2013, 2016

#6

13.11.2018 23:33:59

IgorBoot,
При вставке, как у вас было, весь диапазон указанный ставится в соответвии с полученным массивом который формируется первой формулой, но у вас там только одно значение. Попробуйте введите ={1;2;3;4} в ячейку. потом выделив четыре ячейки ввести как формулу массива. получится 1,2,3,4 в каждой из них, но если сделать тоже но ={1} во всех будет 1.
Copy-past означает копирование формулы в диапазон, а не повторение. операции.
но я б сделал так

Код
Selection.AutoFill Destination:=Range("G13:G16"), Type:=xlFillDefault

Изменено: БМВ13.11.2018 23:34:17

По вопросам из тем форума, личку не читаю.

 

IgorBoot

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

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

#7

13.11.2018 23:34:30

Уважаемый

БМВ

Код
=MAX(IF($B$10:INDEX(B:B;$E$4)=F13;$C$10:INDEX(C:C;$E$4)))

Я прошу прощения, но данная формула выдает ошибку 1004

Ее я запускал и с FormulaArray  и просто с Formula

Изменено: IgorBoot13.11.2018 23:35:35

 

vikttur

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

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

Где? В сообщении она вообще не работает…

 

БМВ

Модератор

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

Excel 2013, 2016

просто БМВ достаточно.
Там м=и ваша формула и рядом моя, макрос для вашей.

Изменено: БМВ13.11.2018 23:55:37

По вопросам из тем форума, личку не читаю.

 

IgorBoot

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

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

БМВ

, Спасибо за решение, к большому сожалению я пока еще не знаю таких тонкостей работы с VBA.
Только я  понять не могу.
Я руками очистил Range(«G13:G16»).
Начал руками компилировать, и на строке
Selection.AutoFill Destination:=Range(«G13:G16»), Type:=xlFillDefault
Выдалась ошибка 1004 «Метод AutoFill из класса Range завершен неверно»
Даже если взять за базу мою «Криворукость», то почему собственно ошибка возникает?

Изменено: IgorBoot13.11.2018 23:53:15

 

IgorBoot

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

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

Уважаемый

vikttur

.
Если Ваш вопрос был адресован мне, то прошу прощения, я Вас не понял.

 

БМВ

Модератор

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

Excel 2013, 2016

#12

13.11.2018 23:55:13

это мой косяк и криворукость

Код
Sub Dvssyl_Array()
With Cells(13, 7)
    .FormulaArray = "=MAX(IF(INDIRECT(""R10C[-5]:R""&R4C5&""C[-5]"",FALSE)=RC[-1],INDIRECT(""R10C[-4]:R""&R4C5&""C[-4]"",FALSE)))"
    .AutoFill Destination:=Range("G13:G16"), Type:=xlFillDefault
End With
End Sub

По вопросам из тем форума, личку не читаю.

 

Юрий М

Модератор

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

Контакты см. в профиле

#13

13.11.2018 23:56:49

Цитата
БМВ написал:
это мой косяк

Да никто его отбирать и не собирался )

 

БМВ

Модератор

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

Excel 2013, 2016

Off
время тяжёлое , завистников много.

Я ваще не понял, чего я тут по двум фронтам отдуваюсь? Игоря опять на разговоры за жизнь потянуло, где все? :-)

По вопросам из тем форума, личку не читаю.

 

IgorBoot

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

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

БМВ

спасибо большое за показанный метод.
Что-то очень близкое я встречал на этом форуме, но к сожалению адаптировать не смог.
Отдельное спасибо за » Метод AutoFill «.
И немного не по теме, но с некоторой толикой сожаления приходится констатировать, что в некоторых моментах без «биения головой в стену» движение дальше не возможно. Это я исключительно про себя.
Еще раз Благодарю Вас. Спасибо Вам большое.

 

БМВ

Модератор

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

Excel 2013, 2016

IgorBoot, не переживайте, на ошибках учатся. Те кто тут сегодня блещут, не сразу такими родились, хотя вот малыш под вопросом :-)

По вопросам из тем форума, личку не читаю.

 

vikttur

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

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

#17

14.11.2018 00:07:21

Цитата
IgorBoot написал: я Вас не понял.

Показывать «выдает ошибку» нужно в файле

 

Добрый вечер!

Подскажите, как правильно записать в ячейку AO8 формулу {=МИН(ЕСЛИ(R:R=AN8;N:N))} в VBA, для поиска минимального значения по условию.
На работе старая версия офиса, функции МИНЕСЛИ нет.
Написал код Range(«AO8»).Formula = «{=MIN(IF(R:R=AN8;N:N))}» но он не работает.
Можно ли как то использовать комбинацию +^~ в качестве Ctrl+Shift+Enter.

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

  • Пример.xlsx (23.96 КБ)

 

Ігор Гончаренко

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

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

#19

06.03.2022 05:36:45

Код
Sub Macro1()
  Range("AO8").FormulaArray = "=MIN(IF(C[-23]=RC[-1],C[-27]))"
  Range("AO8").Copy Range("AO9:AO11")
End Sub

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Роман Дементьев

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

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

#20

06.03.2022 08:20:33

Спасибо!!!!!

Содержание

  1. Свойство Range.FormulaLocal (Excel)
  2. Синтаксис
  3. Замечания
  4. Пример
  5. Поддержка и обратная связь
  6. Вставить формулу массива в Excel VBA
  7. Excel vba вставить формулу массива
  8. Excel vba вставить формулу массива
  9. Excel vba вставить формулу массива

Свойство Range.FormulaLocal (Excel)

Возвращает или задает формулу для объекта, используя ссылки в стиле A1 на языке пользователя. Для чтения и записи, Variant.

Синтаксис

expression. FormulaLocal

выражение: переменная, представляющая объект Range.

Замечания

Если ячейка содержит константу, это свойство возвращает эту константу. Если ячейка пуста, свойство возвращает пустую строку. Если ячейка содержит формулу, свойство возвращает формулу в виде строки в том же формате, в котором она будет отображаться в строке формул (включая знак равенства).

Если присвоить значение или формулу ячейки для даты, Microsoft Excel проверяет, отформатирована ли эта ячейка с помощью одного из форматов даты или времени. В противном случае числовой формат изменяется на формат короткой даты по умолчанию.

Если диапазон состоит из одного или двух измерений, можно установить формулу для массива Visual Basic с теми же размерами. Аналогично, можно поместить формулу в массив Visual Basic.

При установке формулы в диапазоне с несколькими ячейками все ячейки в диапазоне заполняются формулой.

Пример

Предположим, что вы ввели формулу =SUM(A1:A10) в ячейку A11 на листе на одном листе, используя версию Microsoft Excel на американском английском языке. Если затем открыть книгу на компьютере под управлением немецкой версии и выполнить следующий пример, в этом примере отображается формула =SUMME(A1:A10) в окне сообщения.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Вставить формулу массива в Excel VBA

Я записал формулу массива, чтобы вставить в VBA. Вот что у меня после записи. Однако когда я запускаю макрос, он просто не работает.

Из-за отрицательного знака?

Из формулы Excel

Ошибка 1004 — Невозможно установить свойство FormulaArray класса Range.

Прошу прощения за формат кода. Это выглядело ужасно.

Предел вставки массива формул составляет 255 символов с VBA.

Это означает, что мне нужно будет создать диапазоны для ячеек. Спасибо! Могу я спросить, откуда у вас эта информация. Я хочу это проверить.

Есть крайний вариант: использовать человека.

Пусть макрос поместит формулу в ячейку как String, а пользователь завершит процесс:

Я ПОНИМАЮ! Это творчески. Спасибо!

Или вы можете разбить длинную формулу на несколько частей и заменить ее в конце фактической формулой, как показано ниже .

Это еще один изящный способ сделать это! Потрясающие

@OliverBird Спасибо! Любая автоматизация будет неполной, если вы вынуждены попросить пользователя выполнить некоторые действия вручную. Поэтому для меня на самом деле нет никакого смысла вводить формулу как обычную формулу, а затем просить пользователя повторно ввести ее как формулу массива. 🙂

Источник

Excel vba вставить формулу массива

Модератор форума: китин, _Boroda_

Мир MS Excel » Вопросы и решения » Вопросы по VBA » Вычисление формулы массива через VBA и запись результата (Макросы/Sub)

Вычисление формулы массива через VBA и запись результата

matigovas Дата: Суббота, 31.03.2018, 08:26 | Сообщение № 1

Народ с форума помог с задачей, но теперь она усложнилась. Есть формула массива

и она работает как надо, но проблема в том, что таких формул стало очень много и они тормозят работу как Excel, так и людей. Формулы массива идут последовательно в строке начиная со столбца J и грубо говоря до «бесконечности». Самый простой выход, который я вижу — это вычисление формул массива через макрос по нажатию кнопки и помещение результата, скажем в ячейку J15 и дальше по строке. Т.е. само вычисление происходит внутри vba, а итогом становится лишь результат в ячейке.

Народ с форума помог с задачей, но теперь она усложнилась. Есть формула массива

и она работает как надо, но проблема в том, что таких формул стало очень много и они тормозят работу как Excel, так и людей. Формулы массива идут последовательно в строке начиная со столбца J и грубо говоря до «бесконечности». Самый простой выход, который я вижу — это вычисление формул массива через макрос по нажатию кнопки и помещение результата, скажем в ячейку J15 и дальше по строке. Т.е. само вычисление происходит внутри vba, а итогом становится лишь результат в ячейке. matigovas

Сообщение Народ с форума помог с задачей, но теперь она усложнилась. Есть формула массива

и она работает как надо, но проблема в том, что таких формул стало очень много и они тормозят работу как Excel, так и людей. Формулы массива идут последовательно в строке начиная со столбца J и грубо говоря до «бесконечности». Самый простой выход, который я вижу — это вычисление формул массива через макрос по нажатию кнопки и помещение результата, скажем в ячейку J15 и дальше по строке. Т.е. само вычисление происходит внутри vba, а итогом становится лишь результат в ячейке. Автор — matigovas
Дата добавления — 31.03.2018 в 08:26

Источник

Excel vba вставить формулу массива

Pelena, Елена, тут более широкий вопрос и не всегда СУММПРОИЗВ выручит.

adamm1603, по ссылке метод интересный и возможен, но не в вашем случае, так как придется разбивать формулу на части, при этом первая должна работать без второй. Если для единичной это можно сделать руками, то при том что вы хотите, автоматизировать трудно. Собственно там и написано
If the long formula can be broken into parts, where the second part can be replaced by a dummy function, this approach can be used…
дело в том что Replace тоже не всемогущь и не позволяет заменить что-то, на строку более 255 символов.

Pelena, Елена, тут более широкий вопрос и не всегда СУММПРОИЗВ выручит.

adamm1603, по ссылке метод интересный и возможен, но не в вашем случае, так как придется разбивать формулу на части, при этом первая должна работать без второй. Если для единичной это можно сделать руками, то при том что вы хотите, автоматизировать трудно. Собственно там и написано
If the long formula can be broken into parts, where the second part can be replaced by a dummy function, this approach can be used…
дело в том что Replace тоже не всемогущь и не позволяет заменить что-то, на строку более 255 символов. bmv98rus

Замечательный Временно просто медведь , процентов на 20.

Ответить

Сообщение Pelena, Елена, тут более широкий вопрос и не всегда СУММПРОИЗВ выручит.

adamm1603, по ссылке метод интересный и возможен, но не в вашем случае, так как придется разбивать формулу на части, при этом первая должна работать без второй. Если для единичной это можно сделать руками, то при том что вы хотите, автоматизировать трудно. Собственно там и написано
If the long formula can be broken into parts, where the second part can be replaced by a dummy function, this approach can be used…
дело в том что Replace тоже не всемогущь и не позволяет заменить что-то, на строку более 255 символов. Автор — bmv98rus
Дата добавления — 19.07.2019 в 09:53

Pelena Дата: Пятница, 19.07.2019, 10:08 | Сообщение № 25

Я говорю о данной конкретной формуле, ессно.

В своё время тоже делала через Replace. Были бы данные в файле, а то на пустых ячейках неинтересно проверять)

Я говорю о данной конкретной формуле, ессно.

В своё время тоже делала через Replace. Были бы данные в файле, а то на пустых ячейках неинтересно проверять) Pelena

«Черт возьми, Холмс! Но как. »
Ю-money 41001765434816

Ответить

Сообщение Я говорю о данной конкретной формуле, ессно.

В своё время тоже делала через Replace. Были бы данные в файле, а то на пустых ячейках неинтересно проверять) Автор — Pelena
Дата добавления — 19.07.2019 в 10:08

bmv98rus Дата: Пятница, 19.07.2019, 10:30 | Сообщение № 26

Замечательный Временно просто медведь , процентов на 20.

adamm1603 Дата: Пятница, 19.07.2019, 13:12 | Сообщение № 27

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

1. через имена, думаю не менее проблемный)
2. СУММПРОИЗВ, стоит попробовать!
3. sendkeys, тут я пока в полном тупике, скоро английский выучу, читая буржуйские сайты)

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

1. через имена, думаю не менее проблемный)
2. СУММПРОИЗВ, стоит попробовать!
3. sendkeys, тут я пока в полном тупике, скоро английский выучу, читая буржуйские сайты) adamm1603

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

1. через имена, думаю не менее проблемный)
2. СУММПРОИЗВ, стоит попробовать!
3. sendkeys, тут я пока в полном тупике, скоро английский выучу, читая буржуйские сайты) Автор — adamm1603
Дата добавления — 19.07.2019 в 13:12

Источник

Excel vba вставить формулу массива

Модератор форума: китин, _Boroda_

Мир MS Excel » Вопросы и решения » Вопросы по VBA » Как вставить формулу массива в видимые ячейки фильтра? (Макросы/Sub)

Как вставить формулу массива в видимые ячейки фильтра?

machodg Дата: Воскресенье, 03.12.2017, 17:33 | Сообщение № 1
Nic70y Дата: Воскресенье, 03.12.2017, 20:55 | Сообщение № 2
machodg Дата: Воскресенье, 03.12.2017, 21:35 | Сообщение № 3

Спасибо,
но к сожалению нужно макросом, т.к. этот фаил пересылается «чайникам», которые должны лишь в столбец «Н» вписать количества и дальше посмотреть на результат путем всего лишь клика на ячейку «Заказ». (на самом деле этот фаил — небольшой фрагмент от большой статистической системы)

Желаю доброй ночи.

Спасибо,
но к сожалению нужно макросом, т.к. этот фаил пересылается «чайникам», которые должны лишь в столбец «Н» вписать количества и дальше посмотреть на результат путем всего лишь клика на ячейку «Заказ». (на самом деле этот фаил — небольшой фрагмент от большой статистической системы)

Желаю доброй ночи. machodg

Сообщение Спасибо,
но к сожалению нужно макросом, т.к. этот фаил пересылается «чайникам», которые должны лишь в столбец «Н» вписать количества и дальше посмотреть на результат путем всего лишь клика на ячейку «Заказ». (на самом деле этот фаил — небольшой фрагмент от большой статистической системы)

Желаю доброй ночи. Автор — machodg
Дата добавления — 03.12.2017 в 21:35

Nic70y Дата: Понедельник, 04.12.2017, 07:40 | Сообщение № 4
machodg Дата: Понедельник, 04.12.2017, 12:49 | Сообщение № 5

«], т.е. SHIFT+CTRL+ENTER для перевода постой формулы в формулу массива. (посмотрите код в примере):

Set Myrange = Application.Range(Cells(FirstRow, 8), Cells(LastRow, 8))

For Each c In Myrange.SpecialCells(xlVisible)
c.Select
With c
SendKeys «^+

»
DoEvents
End With
Next c

«], т.е. SHIFT+CTRL+ENTER для перевода постой формулы в формулу массива. (посмотрите код в примере):

Set Myrange = Application.Range(Cells(FirstRow, 8), Cells(LastRow, 8))

For Each c In Myrange.SpecialCells(xlVisible)
c.Select
With c
SendKeys «^+

»
DoEvents
End With
Next c

«], т.е. SHIFT+CTRL+ENTER для перевода постой формулы в формулу массива. (посмотрите код в примере):

Set Myrange = Application.Range(Cells(FirstRow, 8), Cells(LastRow, 8))

For Each c In Myrange.SpecialCells(xlVisible)
c.Select
With c
SendKeys «^+

»
DoEvents
End With
Next c

machodg Дата: Понедельник, 04.12.2017, 13:03 | Сообщение № 6
Serge_007 Дата: Понедельник, 04.12.2017, 14:15 | Сообщение № 7
sboy Дата: Понедельник, 04.12.2017, 14:23 | Сообщение № 8
bmv98rus Дата: Понедельник, 04.12.2017, 15:46 | Сообщение № 9

Замечательный Временно просто медведь , процентов на 20.

Nic70y Дата: Понедельник, 04.12.2017, 16:07 | Сообщение № 10
_Boroda_ Дата: Понедельник, 04.12.2017, 17:59 | Сообщение № 11

Ответить

machodg Дата: Вторник, 05.12.2017, 02:04 | Сообщение № 12

[/vba]
Соответственно и цикл по заполнению ячеек не понадобился:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim FirstRow, LastRow As Integer

If Target.Address = «$G$2» And Cells(1, 1) = 1 Then
Cells(1, 1) = 0
Application.ScreenUpdating = 0
With Application
.Calculation = xlAutomatic
.MaxChange = 0.001
End With

If ActiveSheet.FilterMode = True Then
ActiveSheet.ShowAllData
End If

If Cells(3, 7) = 0 Or Cells(3, 7) = «» Then
FirstRow = Range(«G2»).End(xlDown).Row
Else
FirstRow = 3
End If
LastRow = Columns(7).Rows(1040000).End(xlUp).Row

‘1) Ustanovka AutoFiltra
Selection.AutoFilter Field:=7, Criteria1:=»<>«

‘2)Vstavka formul v vidimie iacheiki

Cells(FirstRow, 9) = _
«=IF(RC7<>0,IF(RC3=»»A»»,SUMIF(R3C3:R2186C3,»»A»»,R3C7:R2186C7),IF(RC3=»»B»»,SUMIF(R3C3:R2186C3,»»B»»,R3C7:R2186C7),SUMIF(R3C3:R2186C3,»»C»»,R3C7:R2186C7)))/SUM(R3C7:R2186C7),»»-«»)»

Range(Cells(FirstRow, 9), Cells(LastRow, 9)).Select
Selection.SpecialCells(xlCellTypeVisible).FillDown

Cells(FirstRow, 8).FormulaArray = _
«=SUM(IF(R3C[-5]:R2186C[-5]=RC[-5],R3C[-2]:R2186C[-2]/R3C[-3]:R2186C[-3]*R3C[-1]:R2186C[-1]))/(SUM(IF(R3C[-5]:R2186C[-5]<>«»»»,R3C[-2]:R2186C[-2]/R3C[-3]:R2186C[-3]*R3C[-1]:R2186C[-1])))»

Range(Cells(FirstRow, 8), Cells(LastRow, 8)).Select
Selection.SpecialCells(xlCellTypeVisible).FillDown

End If
Cells(1, 1) = 1
Application.ScreenUpdating = 1
End Sub

Еще раз большое спасибо.
Всем желаю успехов.

[/vba]
Соответственно и цикл по заполнению ячеек не понадобился:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim FirstRow, LastRow As Integer

If Target.Address = «$G$2» And Cells(1, 1) = 1 Then
Cells(1, 1) = 0
Application.ScreenUpdating = 0
With Application
.Calculation = xlAutomatic
.MaxChange = 0.001
End With

If ActiveSheet.FilterMode = True Then
ActiveSheet.ShowAllData
End If

If Cells(3, 7) = 0 Or Cells(3, 7) = «» Then
FirstRow = Range(«G2»).End(xlDown).Row
Else
FirstRow = 3
End If
LastRow = Columns(7).Rows(1040000).End(xlUp).Row

‘1) Ustanovka AutoFiltra
Selection.AutoFilter Field:=7, Criteria1:=»<>«

‘2)Vstavka formul v vidimie iacheiki

Cells(FirstRow, 9) = _
«=IF(RC7<>0,IF(RC3=»»A»»,SUMIF(R3C3:R2186C3,»»A»»,R3C7:R2186C7),IF(RC3=»»B»»,SUMIF(R3C3:R2186C3,»»B»»,R3C7:R2186C7),SUMIF(R3C3:R2186C3,»»C»»,R3C7:R2186C7)))/SUM(R3C7:R2186C7),»»-«»)»

Range(Cells(FirstRow, 9), Cells(LastRow, 9)).Select
Selection.SpecialCells(xlCellTypeVisible).FillDown

Cells(FirstRow, 8).FormulaArray = _
«=SUM(IF(R3C[-5]:R2186C[-5]=RC[-5],R3C[-2]:R2186C[-2]/R3C[-3]:R2186C[-3]*R3C[-1]:R2186C[-1]))/(SUM(IF(R3C[-5]:R2186C[-5]<>«»»»,R3C[-2]:R2186C[-2]/R3C[-3]:R2186C[-3]*R3C[-1]:R2186C[-1])))»

Range(Cells(FirstRow, 8), Cells(LastRow, 8)).Select
Selection.SpecialCells(xlCellTypeVisible).FillDown

End If
Cells(1, 1) = 1
Application.ScreenUpdating = 1
End Sub

Еще раз большое спасибо.
Всем желаю успехов. machodg

[/vba]
Соответственно и цикл по заполнению ячеек не понадобился:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim FirstRow, LastRow As Integer

If Target.Address = «$G$2» And Cells(1, 1) = 1 Then
Cells(1, 1) = 0
Application.ScreenUpdating = 0
With Application
.Calculation = xlAutomatic
.MaxChange = 0.001
End With

If ActiveSheet.FilterMode = True Then
ActiveSheet.ShowAllData
End If

If Cells(3, 7) = 0 Or Cells(3, 7) = «» Then
FirstRow = Range(«G2»).End(xlDown).Row
Else
FirstRow = 3
End If
LastRow = Columns(7).Rows(1040000).End(xlUp).Row

‘1) Ustanovka AutoFiltra
Selection.AutoFilter Field:=7, Criteria1:=»<>«

‘2)Vstavka formul v vidimie iacheiki

Cells(FirstRow, 9) = _
«=IF(RC7<>0,IF(RC3=»»A»»,SUMIF(R3C3:R2186C3,»»A»»,R3C7:R2186C7),IF(RC3=»»B»»,SUMIF(R3C3:R2186C3,»»B»»,R3C7:R2186C7),SUMIF(R3C3:R2186C3,»»C»»,R3C7:R2186C7)))/SUM(R3C7:R2186C7),»»-«»)»

Range(Cells(FirstRow, 9), Cells(LastRow, 9)).Select
Selection.SpecialCells(xlCellTypeVisible).FillDown

Cells(FirstRow, 8).FormulaArray = _
«=SUM(IF(R3C[-5]:R2186C[-5]=RC[-5],R3C[-2]:R2186C[-2]/R3C[-3]:R2186C[-3]*R3C[-1]:R2186C[-1]))/(SUM(IF(R3C[-5]:R2186C[-5]<>«»»»,R3C[-2]:R2186C[-2]/R3C[-3]:R2186C[-3]*R3C[-1]:R2186C[-1])))»

Range(Cells(FirstRow, 8), Cells(LastRow, 8)).Select
Selection.SpecialCells(xlCellTypeVisible).FillDown

End If
Cells(1, 1) = 1
Application.ScreenUpdating = 1
End Sub

Еще раз большое спасибо.
Всем желаю успехов. Автор — machodg
Дата добавления — 05.12.2017 в 02:04

Источник

Adblock
detector

Excel VBA (Visual Basic for Applications) is where spreadsheets meet programming. Although not as complex or powerful as the average programming language, Excel VBA can get very difficult to grasp for all but the most determined of learners. At the same time, the applications and capabilities of VBA are enormous. If you want to truly master Excel, learning VBA is a must. This course on advanced Excel will help you get started.

In this tutorial, we will learn more about one of Excel’s most powerful features, the VBA array, and how to use it in our spreadsheets.

What is an Array?

The dictionary meaning of array is “an ordered arrangement”. In programming and Excel, the meaning is quite similar, except that an array here refers to an “ordered arrangement of data”.

Arrays are primarily used to group or classify data of similar type. In function, it’s similar to a variable, except that a variable can only hold a single item, while an array can hold multiple items.

For example, if I have a list of animals that I want to assign variables to, I can do the following:

A = “Horse”

B = “Dog”

C = “Cat”

D = “Cow”

E = “Duck”

This is just long and tedious. Instead, I can use an array like this:

animals = array(“Horse”, “Dog”, “Cat”, Cow”, “Duck”)

So instead of declaring five separate variables, we declared only one array that could hold all five of our items.

The best part? We can refer or extract any particular item whenever we want. This makes arrays especially powerful for programming.

Arrays are the tool power users turn to when built-in Excel functions fail them. Arrays can be used to perform tasks seemingly impossible to undertake using ordinary formulas. They might sound complicated, but once you get the hang of them, you’ll use them in all your spreadsheets.

Like variables, arrays in VBA are declared using Dim. Besides the array name, you also need to specify the number and type of values the array will store.

The full syntax looks like this:

Dim ExampleArray(6) As String

Where:

Dim = Command for declaring variables/arrays

ExampleArray = Array name

(6) = Number of values to be stored in the array*

As String = The type of data stored in the array

* In VBA, as in most programming languages, count starts from 0. Hence, (6) actually means that there are 7 stored values (from 0 to 6). If you want to count from 1 instead, you would write (1 to 6), like this:

Dim MyArray(1 to 6) As String

Learn more about arrays in Excel in this advanced online training course for Excel 2013.

How to Use Excel VBA Array

The best way to understand how arrays work in Excel is to create one ourselves.

Step 1: Enable Developer Tab

The first step is to enable the Developer tab in Excel. This will enable us to create formulas and macros.

  • Go to File -> Options -> Customize Ribbon.

  • In the Main Tabs, make sure that Developer is selected.

Step 2: Enable Macros

Before we can start creating our array, we will need to enable macros (which are disabled by default for security purposes).

  • Go to File -> Options -> Trust Center

  • Click on Trust Center Settings

  • In the window that pops up, click on Macro Settings

  • Select Enable all macros

Step 3: Create a Button

Before writing our little VBA program, we will first create a button that can run it.

  • Open the Developer tab and click on ‘Insert’

  • Select ‘Button’ under ‘Form Control’ as shown:

  • Click and drag anywhere in the worksheet to create your button.

  • The Assign Macro dialog box will pop up. Here, you can give a custom name to your button, or you can leave it as is. Once you’ve selected the name, click on New

  • The Microsoft Visual Basic for Applications window will pop open. You can also access it by press ALT + F11.

  • In the main code editor window, type in the following program, right after ‘Sub Button1_Click()’:

Dim CustomerName(1 to 10) As String
For i = 1 to 10
CustomerName(i) = InputBox(“Please Enter the Customer Name”)
Cells(i, 1) = CustomerName(i)
Next

  • Save the program by clicking on the save icon. Enter a name in the save dialog box and make sure to choose Excel Macro-Enabled Workbook

Your program is now associated with the button. Pressing the button will trigger the VBA program

New to Excel? This fast track course on Excel will help you get started.

Step 4: Run the Program

Close the VBA window (ALT + F11) after saving the program. You will now see your original worksheet with the button.

Click the button (if the button is not enabled, try clicking on any cell to deselect it before clicking). A prompt asking you to enter “Please Enter Customer Name” (or whatever else you wrote in the program) will pop-up.

Since we set our range in the formula from 1 to 10, the prompt will ask for our input 10 times. Whatever values you enter in the dialog box will automatically fill up the first column:

That’ it! You’ve successfully created a VBA macro using an array!

Breaking it Down: Understanding the VBA Array Formula

Before we leave, let’s take another look at the VBA array formula we used above:

Sub Button1_Click()
Dim CustomerName(1 To 10) As String
For i = 1 To 10
CustomerName(i) = InputBox("Please Enter the Customer Name")
Cells(i, 1) = CustomerName(i)
Next
End Sub

Let’s try to understand it a little better:

Sub Button1_Click()

This command is basically used to refer to the button we created in our workbook. Button1 is the name of our button; Click() is the action that triggers it.

Dim CustomerName(1 to 10) As String

This is our actual array. Here:

Dim = Command used to assign variables and arrays

CustomerName = Name of array

(1 to 10) = The number of values stored in the array.

As String = This tells Excel that the values to be stored are String, not numbers (numbers would be Integer)

Moving on

For i = 1 to 10

This is a VBA for loop. It tells VBA to go through the values 1 to 10 sequentially.

CustomerName(i) = InputBox("Please Enter the Customer Name")

Here, CustomerName(i) cycles through i (from 1 to 10), assigning each the value entered in the InputBox.

Cells(i, 1) = CustomerName(i)

This tells Excel to enter the values of i accepted in the previous line in the first column. If you wanted to enter them in the second column, you would write Cells(i, 2)

Next

Every For loop must end with a Next command.

End Sub

This signals that the program is over.

Now that you know how to use an array, why not take a course like Advanced Excel Training that will introduce you to more advanced Excel concepts, including how to make use of VBA arrays.

1 Introduction

The Range.FormulaArray property is used to set or return the array formula of a range and works in a very similar way to the more familiar Range.Formula property. However, because of the fact that it is working in relation to array formulas, there are more restrictions to consider and it is slightly more difficult to use. In the context of this article, an ‘array formula’ can be considered to mean a formula which has been entered into the formula bar using CTRL+SHIFT+ENTER rather than ENTER, so that it has been enclosed by parentheses { }.

2 Returning A Formula From A Range

If you want to return a formula from a single cell, the Range.Formula and Range.FormulaArray properties both return exactly the same result regardless of whether that cell contains an array formula or not.

However, they return different results when they are applied to a contiguous, multi-cell range. If the range is an array range (a block of cells that shares a single array formula) then the FormulaArray property returns that formula. If the range is not an array range but all of the cells contain identical formulas, then the FormulaArray property will also return that common formula. If the range is not an array range and the cells do not contain identical formulas, then the FormulaArray property returns Null. In all three scenarios, the Formula property will return an array of Variants, with each element of the array representing a formula from each cell within the range.

3 Setting An Array Formula In A Range

According to the Remarks section in ‘Range.FormulaArray Property’ topic in the VBA help file, R1C1 reference style rather than A1 reference style should be used when setting an array formula. This isn’t strictly true, although it may make problem-shooting runtime errors more straightforward. I find A1 notation much easier to use, so I will use it in all the following examples and I’ll discuss the R1C1 vs. A1 reference style question in the problem-shooting section later on.

3.1 Setting A Single-Cell Array Formula

The two points to note are that the = sign at the beginning of the string is optional and that you should not include the parentheses { } which will automatically surround the array formula once it has been assigned.

'put array formula {=FREQUENCY(A2:A10, B2:B4)} into cell E2
Sheet1.Range("E2").FormulaArray = "=FREQUENCY(A2:A10, B2:B4)"

 3.2 Setting A Multi-Cell Array Formula

If the intention is for the block of cells to be an array range (sharing a single formula) then it is as straightforward as the previous example:

'put array formula {=A2:A10="hello"} into cells C2:C10
Sheet1.Range("C2:C10").FormulaArray = "=A2:A10=""hello"""

If the intention is for each cell in the block to have its own array formula then a little bit more work has to be done. Let’s compare a few different options using this array formula as an example:

{=MAX(IF((($E$2:$E$10=A2)+($F$2:$F$10=B2))=1,$G$2:$G$10))}

This formula returns the maximum value in I2:I10 where either (but not both) of the corresponding cells in column G equals A2 or column H equals B2.

Because we want the A2 and B2 references to adjust as we ‘fill’ the array formula down the column, we cannot use the Range.FormulaArray property as we have previously.

The first option is to use a loop, for example:

Sub Option1()

    Dim r As Long

    For r = 2 To 5
        Sheet1.Cells(r, 3).FormulaArray = _
          "=MAX(IF((($E$2:$E$10=A" & CStr(r) & ")+($F$2:$F$10=B" & CStr(r) & "))=1,$G$2:$G$10))"
    Next r

End Sub

Every formula will be calculated irrespective of calculation settings with this option.

The second option is to populate the first cell and then copy/paste or fill it down:

Sub Option2()

    Sheet1.Range("C2").FormulaArray = _
        "=MAX(IF((($E$2:$E$10=A2)+($F$2:$F$10=B2))=1,$G$2:$G$10))"

    Sheet1.Range("C2:C5").FillDown

End Sub

This method will copy not only fill down the formulas but also the formats etc., which may be an advantage or a disadvantage depending on the situation. If calculations are set to manual then the ‘filled in’ cells will not be calculated. In my testing this method seems to be the fastest even with calculations set to automatic.

The third option is to populate the first cell and then copy it onto the clipboard and paste special formulas:

Sub Option3()

    Sheet1.Range("C2").FormulaArray = _
        "=MAX(IF((($E$2:$E$10=A2)+($F$2:$F$10=B2))=1,$G$2:$G$10))"

    Sheet1.Range("C2").Copy
    Sheet1.Range("C3:C5").PasteSpecial xlPasteFormulas
    Application.CutCopyMode = False

End Sub

This avoids copying down the formats etc. but in my testing this method seems to be much slower than all the others. If calculations are set to manual then the formulas that have been pasted will not be calculated.

A final option is as follows:

Sub Option4()

    With Sheet1.Range("C2:C5")
        'step 1
        .Formula = "=MAX(IF((($E$2:$E$10=A2)+($F$2:$F$10=B2))=1,$G$2:$G$10))"

        'step 2
        .FormulaArray = .FormulaR1C1
    End With

End Sub

The formula assignment in step 1 can be done with either the Formula or FormulaR1C1 properties. However, the FormulaR1C1 property must be used in step 2 because using the Formula property would cause the relative references to become distorted down the range. This approach performs fairly similarly to the Option 1 loop approach.

3.3 Problem-Shooting

When you’re trying to use the Range.FormulaArray property you may get the following error:

Run-time error ‘1004’: ‘Unable to set the FormulaArray property of the Range class’

 The message doesn’t contain a lot of useful information so determining the cause of the problem can be quite tough. Here are some reasons why you may be getting this error message:

3.3.1 You Are Trying To Change Part Of An Array Range

For example, this code will fail:

'create an array range
Sheet1.Range("C2:C10").FormulaArray = "=A2:A10=""hello"""

'try to change part of an array range gives an ERROR
Sheet1.Range("C2").FormulaArray = "=A2:A10=""hello"""

You have to clear the array range first or change the entire array range at the same time. You can determine if a cell is part of an array range as follows:

With Sheet1
    'create an array range
    .Range("C2:C10").FormulaArray = "=A2:A10=""hello"""

    With .Range("C2")
        'check if C2 is part of an array range
        If .HasArray Then

            'what is the full array range?
            MsgBox .CurrentArray.Address
        End If
    End With
End With
3.3.2 You Are Trying To Put An Array Formula Into A Merged Cell

It is possible to put an array formula into a cell and then merge that cell with other cells, but you cannot put an array formula into a cell that has already been merged. For example, this code will fail:

'create some merged cells
Sheet1.Range("C2:C10").Merge

'try to set an array formula gives an ERROR
Sheet1.Range("C2").FormulaArray = "=A2:A10=""hello"""

You can check if a cell is part of a merged range as follows:

With Sheet1
    'create some merged cells
    .Range("C2:C10").Merge

    'check if C2 is part of a merged range
    With .Range("C2")
        If .MergeArea.Address = .Address Then
            MsgBox "Cell not merged"
        Else
            MsgBox "Cell is merged, merged range = " & .MergeArea.Address
        End If
    End With
End With
3.3.3 Your Array Formula Contains A Syntax Error Such As A Missing Or Invalid Argument
With Sheet1.Range("E2")
    'this will give an error because argument in SUM() function missing
    .FormulaArray = "=SUM()"

    'this will give an error because SUMIF() cannot accept an array data type
    'passed into its 1st or 3rd parameters: http://support.microsoft.com/kb/214286/
    .FormulaArray = "=SUMIF((A2:A19=1)*(B2:B19),B2,C2:C19)"
End With
3.3.4 Your Array Formula Exceeds 255 Characters

This issue is described on the following MS Support article:

http://support.microsoft.com/kb/213181

More specifically:

  • If you are using A1 notation then the R1C1 equivalent must be less than 255 characters. I picked this information up from MS MVP Rory Archibald.
  • If you are using R1C1 notation then the formula must be less than 256 characters.

A workaround is using the Range.Replace() method as demonstrated at DailyDoseOfExcel:
http://www.dailydoseofexcel.com/archives/2005/01/10/entering-long-array-formulas-in-vba/

I always use a variable to build up and hold the string representing the array formula I want to apply. I find it makes my code easier to read and debug. Another useful tip is that the Application.ConvertFormula() method can be used to easily convert strings between A1 and R1C1 notation (as well as toggling relative or absolute referencing).

Вставить формулу массива через vba

Kongа

Дата: Среда, 20.01.2021, 04:14 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 24


Репутация:

0

±

Замечаний:
0% ±


Excel 2013

Здравствуйте, подскажите, пожалуйста как перевести формулу массива в vba, чтобы она использовала диапазон со второй до последней заполненной ячейки в столбце С листа1.
Вот формула:

Код

=СУММ(—(ЧАСТОТА(ЕСЛИ(Лист3!C2:C5<>»»;ЕСЛИ(Лист3!D2:D5=»Мята»;ПОИСКПОЗ(Лист3!C2:C5;Лист3!C2:C5;0)));СТРОКА(Лист3!C2:C5)-СТРОКА(Лист3!X2)+1)>0))

Пыталась занести ее через FormulaLocal
[vba]

Код

Лист2.[D3].FormulaLocal = «=СУММ(—(ЧАСТОТА(ЕСЛИ(‘Лист3’!C2:C» & LastRow & «<>»»»»;ЕСЛИ(‘Лист3’!D2:D» & LastRow & «=» & «»»Мята»»;ПОИСКПОЗ(‘Лист3′!C2:C» & LastRow & «;’Лист3’!C2:C» & LastRow & «;0)));СТРОКА(‘Лист3’!C2:C» & LastRow & «)-СТРОКА(‘Лист3’!X2)+1)>0))»

[/vba]
, но так она встает как обычная формула и тогда встает проблема как её заставить сделаться «массивной». Если делаю, через .FormulaArray, то не получается сделать её с LastRow.

К сообщению приложен файл:

1268884.xlsm
(16.2 Kb)

Сообщение отредактировал KongаСреда, 20.01.2021, 04:47

 

Ответить

китин

Дата: Среда, 20.01.2021, 08:38 |
Сообщение № 2

Группа: Модераторы

Ранг: Экселист

Сообщений: 6973


Репутация:

1063

±

Замечаний:
0% ±


Excel 2007;2010;2016

а если попробовать вместо
[vba][/vba]
[vba][/vba]
поставить?


Не судите очень строго:я пытаюсь научиться
ЯД 41001877306852

 

Ответить

skyfors

Дата: Среда, 20.01.2021, 09:27 |
Сообщение № 3

Группа: Пользователи

Ранг: Новичок

Сообщений: 16


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

[vba]

Код

    With Worksheets(«Лист3»)
        LastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
    End With

         Лист2.[D3].FormulaLocal = _
        «=СУММ(—(ЧАСТОТА(ЕСЛИ(Лист3!C2:C» & LastRow & «<>»»»»;ЕСЛИ(Лист3!D2:D» & LastRow & «=» & «»»Мята»»» & «;ПОИСКПОЗ(Лист3!C2:C» & LastRow & «;Лист3!C2:C» & LastRow & «;0)));СТРОКА(Лист3!C2:C» & LastRow & «)-СТРОКА(Лист3!C2» & «)+1)>0))»
     Лист2.[D3].FormulaArray = Лист2.[D3].Formula

[/vba]

 

Ответить

В формулах листа оператор «=» умеет работать с массивом, но в VBA так не получится.

Можно вычислять как формулу листа:

Debug.Print Application.Evaluate("SumProduct((""Условие 1"" = A4:A10) * E4:H10)")

Но зачем функция листа, если VBA сам может справиться?

Sub uuu()
Dim ArrDir(), ArrSumS()
Dim direct As String
Dim dSum As Double
Dim i As Long, j As Long
    i = 10: j = 8 ' где-то раньше определили последние строку/столбец
    direct = "Условие 1" ' значение для сравнения

    ' значения диапазонов листа записываем в массивы
    With Workbooks(fExp).Sheets(fExpShN)
        ArrDir = .Range("A4:A" & i).Value
        ArrSumS = .Range(.Cells(4, 5), .Cells(i, j)).Value
    End With

    ' переменные i, j уже свободны, используем в циклах
    For i = 1 To UBound(ArrDir) ' цикл по вертикали
        If ArrDir(i, 1) = direct Then
            For j = 1 To UBound(ArrSumS, 2) ' цикл по второй размерности
                dSum = dSum + ArrSumS(i, j) ' сумма
            Next j
        End If
    Next i

    Debug.Print dSum
End Sub

 --------------------------------

Примечания к коду автора:

  • родителя можно определять один раз: оператор With/End Wiht ускоряет обработку и помогает сделать код читабельнее;

  • ссылка на книгу не нужна, если макрос записан в этой же книге;

  • для определения диапазона не обязательно применять .Address;

  • строка Application.WorksheetFunction… в любом случае вызвала бы ошибку: получаемое значение никуда не передается.

Правильно:

.Cells(1,1).Value = Application.WorksheetFunction…

dSum = Application.WorksheetFunction…

MsgBox Application.WorksheetFunction…

This post provides an in-depth look at the VBA array which is a very important part of the Excel VBA programming language. It covers everything you need to know about the VBA array.

We will start by seeing what exactly is the VBA Array is and why you need it.

Below you will see a quick reference guide to using the VBA Array.  Refer to it anytime you need a quick reminder of the VBA Array syntax.

The rest of the post provides the most complete guide you will find on the VBA array.

Related Links for the VBA Array

Loops are used for reading through the VBA Array:
For Loop
For Each Loop

Other data structures in VBA:
VBA Collection – Good when you want to keep inserting items as it automatically resizes.
VBA ArrayList – This has more functionality than the Collection.
VBA Dictionary – Allows storing a KeyValue pair. Very useful in many applications.

The Microsoft guide for VBA Arrays can be found here.

A Quick Guide to the VBA Array

Task Static Array Dynamic Array
Declare Dim arr(0 To 5) As Long Dim arr() As Long
Dim arr As Variant
Set Size See Declare above ReDim arr(0 To 5)As Variant
Get Size(number of items) See ArraySize function below. See ArraySize function below.
Increase size (keep existing data) Dynamic Only ReDim Preserve arr(0 To 6)
Set values arr(1) = 22 arr(1) = 22
Receive values total = arr(1) total = arr(1)
First position LBound(arr) LBound(arr)
Last position Ubound(arr) Ubound(arr)
Read all items(1D) For i = LBound(arr) To UBound(arr)
Next i

Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
For i = LBound(arr) To UBound(arr)
Next i

Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
Read all items(2D) For i = LBound(arr,1) To UBound(arr,1)
  For j = LBound(arr,2) To UBound(arr,2)
  Next j
Next i
For i = LBound(arr,1) To UBound(arr,1)
  For j = LBound(arr,2) To UBound(arr,2)
  Next j
Next i
Read all items Dim item As Variant
For Each item In arr
Next item
Dim item As Variant
For Each item In arr
Next item
Pass to Sub Sub MySub(ByRef arr() As String) Sub MySub(ByRef arr() As String)
Return from Function Function GetArray() As Long()
    Dim arr(0 To 5) As Long
    GetArray = arr
End Function
Function GetArray() As Long()
    Dim arr() As Long
    GetArray = arr
End Function
Receive from Function Dynamic only Dim arr() As Long
Arr = GetArray()
Erase array Erase arr
*Resets all values to default
Erase arr
*Deletes array
String to array Dynamic only Dim arr As Variant
arr = Split(«James:Earl:Jones»,»:»)
Array to string Dim sName As String
sName = Join(arr, «:»)
Dim sName As String
sName = Join(arr, «:»)
Fill with values Dynamic only Dim arr As Variant
arr = Array(«John», «Hazel», «Fred»)
Range to Array Dynamic only Dim arr As Variant
arr = Range(«A1:D2»)
Array to Range Same as dynamic Dim arr As Variant
Range(«A5:D6») = arr

Download the Source Code and Data

Please click on the button below to get the fully documented source code for this article.

What is the VBA Array and Why do You Need It?

A VBA array is a type of variable. It is used to store lists of data of the same type. An example would be storing a list of countries or a list of weekly totals.

In VBA a normal variable can store only one value at a time.

In the following example we use a variable to store the marks of a student:

' Can only store 1 value at a time
Dim Student1 As Long
Student1 = 55

If we wish to store the marks of another student then we need to create a second variable.

In the following example, we have the marks of five students:

VBa Arrays

Student Marks

We are going to read these marks and write them to the Immediate Window.

Note: The function Debug.Print writes values to the Immediate  Window. To view this window select View->Immediate Window from the menu( Shortcut is Ctrl + G)

ImmediateWindow

ImmediateSampeText

As you can see in the following example we are writing the same code five times – once for each student:

' https://excelmacromastery.com/
Public Sub StudentMarks()

    ' Get the worksheet called "Marks"
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Marks")
    
    ' Declare variable for each student
    Dim Student1 As Long
    Dim Student2 As Long
    Dim Student3 As Long
    Dim Student4 As Long
    Dim Student5 As Long

    ' Read student marks from cell
    Student1 = sh.Range("C" & 3).Value
    Student2 = sh.Range("C" & 4).Value
    Student3 = sh.Range("C" & 5).Value
    Student4 = sh.Range("C" & 6).Value
    Student5 = sh.Range("C" & 7).Value

    ' Print student marks
    Debug.Print "Students Marks"
    Debug.Print Student1
    Debug.Print Student2
    Debug.Print Student3
    Debug.Print Student4
    Debug.Print Student5

End Sub

The following is the output from the example:

VBA Arrays

Output

The problem with using one variable per student is that you need to add code for each student. Therefore if you had a thousand students in the above example you would need three thousand lines of code!

Luckily we have arrays to make our life easier. Arrays allow us to store a list of data items in one structure.

The following code shows the above student example using an array:

' ExcelMacroMastery.com
' https://excelmacromastery.com/excel-vba-array/
' Author: Paul Kelly
' Description: Reads marks to an Array and write
' the array to the Immediate Window(Ctrl + G)
' TO RUN: Click in the sub and press F5
Public Sub StudentMarksArr()

    ' Get the worksheet called "Marks"
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Marks")

    ' Declare an array to hold marks for 5 students
    Dim Students(1 To 5) As Long

    ' Read student marks from cells C3:C7 into array
    ' Offset counts rows from cell C2.
    ' e.g. i=1 is C2 plus 1 row which is C3
    '      i=2 is C2 plus 2 rows which is C4
    Dim i As Long
    For i = 1 To 5
        Students(i) = sh.Range("C2").Offset(i).Value
    Next i

    ' Print student marks from the array to the Immediate Window
    Debug.Print "Students Marks"
    For i = LBound(Students) To UBound(Students)
        Debug.Print Students(i)
    Next i

End Sub

The advantage of this code is that it will work for any number of students. If we have to change this code to deal with 1000 students we only need to change the (1 To 5) to (1 To 1000) in the declaration. In the prior example we would need to add approximately five thousand lines of code.

Let’s have a quick comparison of variables and arrays. First we compare the declaration:

        ' Variable
        Dim Student As Long
        Dim Country As String

        ' Array
        Dim Students(1 To 3) As Long
        Dim Countries(1 To 3) As String

Next we compare assigning a value:

        ' assign value to variable
        Student1 = .Cells(1, 1) 

        ' assign value to first item in array
        Students(1) = .Cells(1, 1)

Finally we look at writing the values:

        ' Print variable value
        Debug.Print Student1

        ' Print value of first student in array
        Debug.Print Students(1)

As you can see, using variables and arrays is quite similar.

The fact that arrays use an index(also called a subscript) to access each item is important. It means we can easily access all the items in an array using a For Loop.

Now that you have some background on why arrays are useful let’s go through them step by step.

Two Types of VBA Arrays

There are two types of VBA arrays:

  1. Static – an array of fixed length.
  2. Dynamic(not to be confused with the Excel Dynamic Array) – an array where the length is set at run time.

The difference between these types is mostly in how they are created. Accessing values in both array types is exactly the same. In the following sections we will cover both of these types.

VBA Array Initialization

A static array is initialized as follows:

' https://excelmacromastery.com/
Public Sub DecArrayStatic()

    ' Create array with locations 0,1,2,3
    Dim arrMarks1(0 To 3) As Long

    ' Defaults as 0 to 3 i.e. locations 0,1,2,3
    Dim arrMarks2(3) As Long

    ' Create array with locations 1,2,3,4,5
    Dim arrMarks3(1 To 5) As Long

    ' Create array with locations 2,3,4 ' This is rarely used
    Dim arrMarks4(2 To 4) As Long

End Sub

VBA Arrays

An Array of 0 to 3

As you can see the length is specified when you declare a static array. The problem with this is that you can never be sure in advance the length you need. Each time you run the Macro you may have different length requirements.

If you do not use all the array locations then the resources are being wasted. So if you need more locations you can use ReDim but this is essentially creating a new static array.

The dynamic array does not have such problems. You do not specify the length when you declare it. Therefore you can then grow and shrink as required:

' https://excelmacromastery.com/
Public Sub DecArrayDynamic()

    ' Declare  dynamic array
    Dim arrMarks() As Long

    ' Set the length of the array when you are ready
    ReDim arrMarks(0 To 5)

End Sub

The dynamic array is not allocated until you use the ReDim statement. The advantage is you can wait until you know the number of items before setting the array length. With a static array you have to state the length upfront.

To give an example. Imagine you were reading worksheets of student marks. With a dynamic array you can count the students on the worksheet and set an array to that length. With a static array you must set the length to the largest possible number of students.

Assigning Values to VBA Array

To assign values to an array you use the number of the location. You assign the value for both array types the same way:

' https://excelmacromastery.com/
Public Sub AssignValue()

    ' Declare  array with locations 0,1,2,3
    Dim arrMarks(0 To 3) As Long

    ' Set the value of position 0
    arrMarks(0) = 5

    ' Set the value of position 3
    arrMarks(3) = 46

    ' This is an error as there is no location 4
    arrMarks(4) = 99

End Sub

VBA Array 2

The array with values assigned

The number of the location is called the subscript or index. The last line in the example will give a “Subscript out of Range” error as there is no location 4 in the array example.

VBA Array Length

There is no native function for getting the number of items in an array. I created the ArrayLength function below to return the number of items in any array no matter how many dimensions:

' https://excelmacromastery.com/
Function ArrayLength(arr As Variant) As Long

    On Error Goto eh
    
    ' Loop is used for multidimensional arrays. The Loop will terminate when a
    ' "Subscript out of Range" error occurs i.e. there are no more dimensions.
    Dim i As Long, length As Long
    length = 1
    
    ' Loop until no more dimensions
    Do While True
        i = i + 1
        ' If the array has no items then this line will throw an error
        Length = Length * (UBound(arr, i) - LBound(arr, i) + 1)
        ' Set ArrayLength here to avoid returing 1 for an empty array
        ArrayLength = Length
    Loop

Done:
    Exit Function
eh:
    If Err.Number = 13 Then ' Type Mismatch Error
        Err.Raise vbObjectError, "ArrayLength" _
            , "The argument passed to the ArrayLength function is not an array."
    End If
End Function

You can use it like this:

' Name: TEST_ArrayLength
' Author: Paul Kelly, ExcelMacroMastery.com
' Description: Tests the ArrayLength functions and writes
'              the results to the Immediate Window(Ctrl + G)
Sub TEST_ArrayLength()
    
    ' 0 items
    Dim arr1() As Long
    Debug.Print ArrayLength(arr1)
    
    ' 10 items
    Dim arr2(0 To 9) As Long
    Debug.Print ArrayLength(arr2)
    
    ' 18 items
    Dim arr3(0 To 5, 1 To 3) As Long
    Debug.Print ArrayLength(arr3)
    
    ' Option base 0: 144 items
    ' Option base 1: 50 items
    Dim arr4(1, 5, 5, 0 To 1) As Long
    Debug.Print ArrayLength(arr4)
    
End Sub

Using the Array and Split function

You can use the Array function to populate an array with a list of items. You must declare the array as a type Variant. The following code shows you how to use this function.

    Dim arr1 As Variant
    arr1 = Array("Orange", "Peach","Pear")

    Dim arr2 As Variant
    arr2 = Array(5, 6, 7, 8, 12)

Arrays VBA

Contents of arr1 after using the Array function

The array created by the Array Function will start at index zero unless you use Option Base 1 at the top of your module. Then it will start at index one. In programming, it is generally considered poor practice to have your actual data in the code. However, sometimes it is useful when you need to test some code quickly.

The Split function is used to split a string into an array based on a delimiter. A delimiter is a character such as a comma or space that separates the items.

The following code will split the string into an array of four elements:

    Dim s As String
    s = "Red,Yellow,Green,Blue"

    Dim arr() As String
    arr = Split(s, ",")

Arrays VBA

The array after using Split

The Split function is normally used when you read from a comma-separated file or another source that provides a list of items separated by the same character.

Using Loops With the VBA Array

Using a For Loop allows quick access to all items in an array. This is where the power of using arrays becomes apparent. We can read arrays with ten values or ten thousand values using the same few lines of code. There are two functions in VBA called LBound and UBound. These functions return the smallest and largest subscript in an array. In an array arrMarks(0 to 3) the LBound will return 0 and UBound will return 3.

The following example assigns random numbers to an array using a loop. It then prints out these numbers using a second loop.

' https://excelmacromastery.com/
Public Sub ArrayLoops()

    ' Declare  array
    Dim arrMarks(0 To 5) As Long

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' Print out the values in the array
    Debug.Print "Location", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

The functions LBound and UBound are very useful. Using them means our loops will work correctly with any array length. The real benefit is that if the length of the array changes we do not have to change the code for printing the values. A loop will work for an array of any length as long as you use these functions.

Using the For Each Loop with the VBA Array

You can use the For Each loop with arrays. The important thing to keep in mind is that it is Read-Only. This means that you cannot change the value in the array.

In the following code the value of mark changes but it does not change the value in the array.

    For Each mark In arrMarks
        ' Will not change the array value
        mark = 5 * Rnd
    Next mark

The For Each is loop is fine to use for reading an array. It is neater to write especially for a Two-Dimensional array as we will see.

    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Using Erase with the VBA Array

The Erase function can be used on arrays but performs differently depending on the array type.

For a static Array the Erase function resets all the values to the default. If the array is made up of long integers(i.e type Long) then all the values are set to zero. If the array is of strings then all the strings are set to “” and so on.

For a Dynamic Array the Erase function DeAllocates memory. That is, it deletes the array. If you want to use it again you must use ReDim to Allocate memory.

Let’s have a look an example for the static array. This example is the same as the ArrayLoops example in the last section with one difference – we use Erase after setting the values. When the value are printed out they will all be zero:

' https://excelmacromastery.com/
Public Sub EraseStatic()

    ' Declare  array
    Dim arrMarks(0 To 3) As Long

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' ALL VALUES SET TO ZERO
    Erase arrMarks

    ' Print out the values - there are all now zero
    Debug.Print "Location", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

We will now try the same example with a dynamic. After we use Erase all the locations in the array have been deleted. We need to use ReDim if we wish to use the array again.

If we try to access members of this array we will get a “Subscript out of Range” error:

' https://excelmacromastery.com/
Public Sub EraseDynamic()

    ' Declare  array
    Dim arrMarks() As Long
    ReDim arrMarks(0 To 3)

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' arrMarks is now deallocated. No locations exist.
    Erase arrMarks

End Sub

Increasing the length of the VBA Array

If we use ReDim on an existing array, then the array and its contents will be deleted.

In the following example, the second ReDim statement will create a completely new array. The original array and its contents will be deleted.

' https://excelmacromastery.com/
Sub UsingRedim()

    Dim arr() As String
    
    ' Set array to be slots 0 to 2
    ReDim arr(0 To 2)
    arr(0) = "Apple"
    
    ' Array with apple is now deleted
    ReDim arr(0 To 3)

End Sub

If we want to extend the length of an array without losing the contents, we can use the Preserve keyword.

When we use Redim Preserve the new array must start at the same starting dimension e.g.

We cannot Preserve from (0 to 2) to (1 to 3) or to (2 to 10) as they are different starting dimensions.

In the following code we create an array using ReDim and then fill the array with types of fruit.

We then use Preserve to extend the length of the array so we don’t lose the original contents:

' https://excelmacromastery.com/
Sub UsingRedimPreserve()

    Dim arr() As String
    
    ' Set array to be slots 0 to 1
    ReDim arr(0 To 2)
    arr(0) = "Apple"
    arr(1) = "Orange"
    arr(2) = "Pear"
    
    ' Reset the length and keep original contents
    ReDim Preserve arr(0 To 5)

End Sub

You can see from the screenshots below, that the original contents of the array have been “Preserved”.

VBA Preserve

Before ReDim Preserve

VBA Preserve

After ReDim Preserve

Word of Caution: In most cases, you shouldn’t need to resize an array like we have done in this section. If you are resizing an array multiple times then you may want to consider using a Collection.

Using Preserve with Two-Dimensional Arrays

Preserve only works with the upper bound of an array.

For example, if you have a two-dimensional array you can only preserve the second dimension as this example shows:

' https://excelmacromastery.com/
Sub Preserve2D()

    Dim arr() As Long
    
    ' Set the starting length
    ReDim arr(1 To 2, 1 To 5)
    
    ' Change the length of the upper dimension
    ReDim Preserve arr(1 To 2, 1 To 10)

End Sub

If we try to use Preserve on a lower bound we will get the “Subscript out of range” error.

In the following code we use Preserve on the first dimension. Running this code will give the “Subscript out of range” error:

' https://excelmacromastery.com/
Sub Preserve2DError()

    Dim arr() As Long
    
    ' Set the starting length
    ReDim arr(1 To 2, 1 To 5)
    
    ' "Subscript out of Range" error
    ReDim Preserve arr(1 To 5, 1 To 5)

End Sub

When we read from a range to an array, it automatically creates a two-dimensional array, even if we have only one column.

The same Preserve rules apply. We can only use Preserve on the upper bound as this example shows:

' https://excelmacromastery.com/
Sub Preserve2DRange()

    Dim arr As Variant
    
    ' Assign a range to an array
    arr = Sheet1.Range("A1:A5").Value
    
    ' Preserve will work on the upper bound only
    ReDim Preserve arr(1 To 5, 1 To 7)

End Sub

Sorting the VBA Array

There is no function in VBA for sorting an array. We can sort the worksheet cells but this could be slow if there is a lot of data.

The QuickSort function below can be used to sort an array.

' https://excelmacromastery.com/
Sub QuickSort(arr As Variant, first As Long, last As Long)
  
  Dim vCentreVal As Variant, vTemp As Variant
  
  Dim lTempLow As Long
  Dim lTempHi As Long
  lTempLow = first
  lTempHi = last
  
  vCentreVal = arr((first + last)  2)
  Do While lTempLow <= lTempHi
  
    Do While arr(lTempLow) < vCentreVal And lTempLow < last
      lTempLow = lTempLow + 1
    Loop
    
    Do While vCentreVal < arr(lTempHi) And lTempHi > first
      lTempHi = lTempHi - 1
    Loop
    
    If lTempLow <= lTempHi Then
    
        ' Swap values
        vTemp = arr(lTempLow)

        arr(lTempLow) = arr(lTempHi)
        arr(lTempHi) = vTemp
      
        ' Move to next positions
        lTempLow = lTempLow + 1
        lTempHi = lTempHi - 1
      
    End If
    
  Loop
  
  If first < lTempHi Then QuickSort arr, first, lTempHi
  If lTempLow < last Then QuickSort arr, lTempLow, last
  
End Sub

You can use this function like this:

' https://excelmacromastery.com/
Sub TestSort()

    ' Create temp array
    Dim arr() As Variant
    arr = Array("Banana", "Melon", "Peach", "Plum", "Apple")
  
    ' Sort array
    QuickSort arr, LBound(arr), UBound(arr)

    ' Print arr to Immediate Window(Ctrl + G)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i

End Sub

Passing the VBA Array to a Sub

Sometimes you will need to pass an array to a procedure. You declare the parameter using parenthesis similar to how you declare a dynamic array.

Passing to the procedure using ByRef means you are passing a reference of the array. So if you change the array in the procedure it will be changed when you return.

Note: When you use an array as a parameter it cannot use ByVal, it must use ByRef. You can pass the array using ByVal making the parameter a variant.

' https://excelmacromastery.com/
' Passes array to a Function
Public Sub PassToProc()
    Dim arr(0 To 5) As String
    ' Pass the array to function
    UseArray arr
End Sub

Public Function UseArray(ByRef arr() As String)
    ' Use array
    Debug.Print UBound(arr)
End Function

Returning the VBA Array from a Function

It is important to keep the following in mind. If you want to change an existing array in a procedure then you should pass it as a parameter using ByRef(see last section). You do not need to return the array from the procedure.

The main reason for returning an array is when you use the procedure to create a new one. In this case you assign the return array to an array in the caller. This array cannot be already allocated. In other words you must use a dynamic array that has not been allocated.

The following examples show this

' https://excelmacromastery.com/
Public Sub TestArray()

    ' Declare dynamic array - not allocated
    Dim arr() As String
    ' Return new array
    arr = GetArray

End Sub

Public Function GetArray() As String()

    ' Create and allocate new array
    Dim arr(0 To 5) As String
    ' Return array
    GetArray = arr

End Function

Using a Two-Dimensional VBA Array

The arrays we have been looking at so far have been one-dimensional arrays. This means the arrays are one list of items.

A two-dimensional array is essentially a list of lists. If you think of a single spreadsheet row as a single dimension then more than one column is two dimensional. In fact a spreadsheet is the equivalent of a two-dimensional array. It has two dimensions – rows and columns.

One small thing to note is that Excel treats a one-dimensional array as a row if you write it to a spreadsheet. In other words, the array arr(1 to 5) is equivalent to arr(1 to 1, 1 to 5) when writing values to the spreadsheet.

The following image shows two groups of data. The first is a one-dimensional layout and the second is two dimensional.

VBA Array Dimension

To access an item in the first set of data(1 dimensional) all you need to do is give the row e.g. 1,2, 3 or 4.

For the second set of data (two-dimensional), you need to give the row AND the column. So you can think of 1 dimensional being multiple columns and one row and two-dimensional as being multiple rows and multiple columns.

Note: It is possible to have more than two dimensions in an array. It is rarely required. If you are solving a problem using a 3+ dimensional array then there probably is a better way to do it.

You declare a two-dimensional array as follows:

Dim ArrayMarks(0 To 2,0 To 3) As Long

The following example creates a random value for each item in the array and the prints the values to the Immediate Window:

' https://excelmacromastery.com/
Public Sub TwoDimArray()

    ' Declare a two dimensional array
    Dim arrMarks(0 To 3, 0 To 2) As String

    ' Fill the array with text made up of i and j values
    Dim i As Long, j As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            arrMarks(i, j) = CStr(i) & ":" & CStr(j)
        Next j
    Next i

    ' Print the values in the array to the Immediate Window
    Debug.Print "i", "j", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

End Sub

You can see that we use a second For loop inside the first loop to access all the items.

The output of the example looks like this:

VBA Arrays

How this Macro works is as follows:

  • Enters the i loop
  • i is set to 0
  • Entersj loop
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • Exit j loop
  • i is set to 1
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • And so on until i=3 and j=2

You may notice that LBound and UBound have a second argument with the value 2. This specifies that it is the upper or lower bound of the second dimension. That is the start and end location for j. The default value 1 which is why we do not need to specify it for the i loop.

Using the For Each Loop

Using a For Each is neater to use when reading from an array.

Let’s take the code from above that writes out the two-dimensional array

    ' Using For loop needs two loops
    Debug.Print "i", "j", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

Now let’s rewrite it using a For each loop. You can see we only need one loop and so it is much easier to write:

    ' Using For Each requires only one loop
    Debug.Print "Value"
    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Using the For Each loop gives us the array in one order only – from LBound to UBound. Most of the time this is all you need.

Reading from a Range to the VBA Array

If you have read my previous post on Cells and Ranges then you will know that VBA has an extremely efficient way of reading from a Range of Cells to an Array and vice versa

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Declare dynamic array
    Dim StudentMarks As Variant

    ' Read values into array from first row
    StudentMarks = Range("A1:Z1").Value

    ' Write the values back to the third row
    Range("A3:Z3").Value = StudentMarks

End Sub

The dynamic array created in this example will be a two dimensional array. As you can see we can read from an entire range of cells to an array in just one line.

The next example will read the sample student data below from C3:E6 of Sheet1 and print them to the Immediate Window:

' https://excelmacromastery.com/
Public Sub ReadAndDisplay()

    ' Get Range
    Dim rg As Range
    Set rg = ThisWorkbook.Worksheets("Sheet1").Range("C3:E6")

    ' Create dynamic array
    Dim StudentMarks As Variant

    ' Read values into array from sheet1
    StudentMarks = rg.Value

    ' Print the array values
    Debug.Print "i", "j", "Value"
    Dim i As Long, j As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        For j = LBound(StudentMarks, 2) To UBound(StudentMarks, 2)
            Debug.Print i, j, StudentMarks(i, j)
        Next j
    Next i

End Sub

VBA 2D Array

Sample Student data

VBA 2D Array Output

Output from sample data

As you can see the first dimension(accessed using i) of the array is a row and the second is a column. To demonstrate this take a look at the value 44 in E4 of the sample data. This value is in row 2 column 3 of our data. You can see that 44 is stored in the array at StudentMarks(2,3).

You can see more about using arrays with ranges in this YouTube video

How To Make Your Macros Run at Super Speed

If your macros are running very slow then you may find this section very helpful. Especially if you are dealing with large amounts of data. The following is a very well-kept secret in VBA

Updating values in arrays is exponentially faster than updating values in cells.

In the last section, you saw how we can easily read from a group of cells to an array and vice versa. If we are updating a lot of values then we can do the following:

1. Copy the data from the cells to an array.
2. Change the data in the array.
3. Copy the updated data from the array back to the cells.

For example, the following code would be much faster than the code below it:

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Read values into array from first row
    Dim StudentMarks  As Variant
    StudentMarks = Range("A1:Z20000").Value

    Dim i As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        ' Update marks here
        StudentMarks(i, 1) = StudentMarks(i, 1) * 2
        '...
    Next i

    ' Write the new values back to the worksheet
    Range("A1:Z20000").Value = StudentMarks

End Sub
' https://excelmacromastery.com/
Sub UsingCellsToUpdate()
    
    Dim c As Variant
    For Each c In Range("A1:Z20000")
        c.Value = ' Update values here
    Next c
    
End Sub

Assigning from one set of cells to another is also much faster than using Copy and Paste:

' Assigning - this is faster
Range("A1:A10").Value = Range("B1:B10").Value

' Copy Paste - this is slower
Range("B1:B1").Copy Destination:=Range("A1:A10")

The following comments are from two readers who used arrays to speed up their macros

“A couple of my projects have gone from almost impossible and long to run into almost too easy and a reduction in time to run from 10:1.” – Dane

“One report I did took nearly 3 hours to run when accessing the cells directly — 5 minutes with arrays” – Jim

You can see more about the speed of Arrays compared to other methods in this YouTube video.

To see a comparison between Find, Match and Arrays it is worth checking out this post by Charles Williams.

Conclusion

The following is a summary of the main points of this post

  1. Arrays are an efficient way of storing a list of items of the same type.
  2. You can access an array item directly using the number of the location which is known as the subscript or index.
  3. The common error “Subscript out of Range” is caused by accessing a location that does not exist.
  4. There are two types of arrays: Static and Dynamic.
  5. Static is used when the length of the array is always the same.
  6. Dynamic arrays allow you to determine the length of an array at run time.
  7. LBound and UBound provide a safe way of find the smallest and largest subscripts of the array.
  8. The basic array is one dimensional. You can also have multidimensional arrays.
  9. You can only pass an array to a procedure using ByRef. You do this like this: ByRef arr() as long.
  10. You can return an array from a function but the array, it is assigned to, must not be currently allocated.
  11. A worksheet with its rows and columns is essentially a two-dimensional array.
  12. You can read directly from a worksheet range into a two-dimensional array in just one line of code.
  13. You can also write from a two-dimensional array to a range in just one line of code.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try  The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Понравилась статья? Поделить с друзьями:
  • Vba excel формула листа
  • Vba excel указать лист
  • Vba excel указание листа
  • Vba excel узнать размерность массива
  • Vba excel узнать последнюю ячейку