Vba на английском excel

After Microsoft Office updated to the 2016 version I found the VBA interface is in German. How can I restore it to English?

My Windows 10 settings are set to English and the local setting preferences are all for English UK as well (dates, decimals etc.).

I set the Office Preference Language to English.

Please find screen-shot attached

Community's user avatar

asked Sep 26, 2018 at 8:56

Cezary Domański's user avatar

3

I tried above solutions and didn’t works for me.
This one works and not need administrator rights.

Close all Office apps.
Open any Office app I.E. Excel

Choose: Options, Language

Select default language for edition: English (this option probably isnt neccessary but I did this when i looked for solution)
Set English from order list as top of language for display
Set English from order list as top of language for help

Looks like VBA language is based on these two options and is selected in order.
My primary language is Polish, and my VBA editor was in Italian.
To change VBA language to English i set order from these lists so English is choosed as first language if something can’t be displayed in Polish. (previously Italian was as number 3 an this list)
VBA Language setup

answered Aug 23, 2020 at 14:25

Robert de Clair's user avatar

Have a look at the setting at Control Panel > Region and Language > Administrative. If it’s showing «Germany/German» for non-unicode programs, you might be able to change it there.


This thread at answers.microsoft.com suggests to have a look at the folder C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.1.

Hello, I’ve had the same problem and finally found the solution. The
language file for VBA editor interface is stored in the following
folder with different subfolders:

C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.1

(you may need to search for VBEUIINTL.dll if you can’t find this
folder on your computer)

in this folder the 1033 subfolder and its contents are for English
interface. The other ones are for different languages. Somehow VBA
chooses the wrong subfolder. So you basically need to copy the
contents of 1033 folder ( as a workaround ):

«C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033APC71ITL.DLL»
«C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033VBE7INTL.DLL»
«C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033VBEUIINTL.DLL»

to the 2052 folder (for chinese for example, may be you have
different), for changing the language.

Before doing this , restart and don’t start any office products. Then
copy the files; overwrite if asked. I also suggest you to take a
backup of VBA7.1 folder in case something goes wrong.

The suggestion to restart seems a bit unneeded to me — just make sure all office programs that support VBA (Excel, Word, Access, PowerPoint, Outlook) are closed.

Also this latter method seems more like treating the symptoms — to me it doesn’t appear to be the correct way of changing the language of your VBE (merely one suboptimal way).

answered Sep 26, 2018 at 9:34

Inarion's user avatar

InarionInarion

5683 silver badges14 bronze badges

8

I had the same issue except my VBA’s interface was French.
Windows 8.1 and Office 2013 were installed with Hungarian language, Regional and «non-unicode» settings are also set to Hungarian.

I have 3 folders in C:Program Files (x86)Common FilesMicrosoft SharedVBAVBA7.1:
— 1033 — English (US)
— 1036 — French
— 1038 — Hungarian
Source of Language Codes: renenyffenegger.ch

Unfortunately I don’t have administrator rights, so I couldn’t modify files or folders inside Program Files (x86).
I don’t understand how but I can modify HKEY_CURRENT_USER in Registry (regedit.exe).

I’m not sure which one was the solution so I share two things.

First of all, you have to close all Office applications.

#1
In HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0CommonLanguageResources there are more REG_MULTI_SZ Values with data like 0;1038;1033;1036.

Delete the unwanted language code from everywhere. (1031 — German, 1036 — French, etc. see link above)
I deleted 1036 which resulted: 0;1038;1033

They will be automatically restored after you start Excel, but don’t worry about it.

#2
In HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0CommonLanguageResourcesEnabledLanguages set unwanted language code from ExplicitOn to Off or On.

It doesn’t matter what you set because after next start of Excel it will be set to On automatically.

In my case one or both of these was the solution and VBA’s interface language is finally English.

answered Apr 9, 2019 at 12:47

Vikitorony's user avatar

This worked for me (Windows 10 user).

All settings> Time & Language> Region & Language.

Under «Preferred Languages», add the language that you want to use.
If that language is already on the list, make sure it’s at the top (you can move it by single-clicking on it and using the up/down arrows on the left).

You’ll notice a comment under the heading that says: «Apps and languages will appear in the first language that they support.»
In my case, the top language was Norwegian and the next on the list was Chinese. VBA for some reason wouldn’t recognize Norwegian, and assumed Chinese would be the next best thing.
I installed English (US), moved it to the top of the list, and restarted my computer. Boom.

answered Jul 8, 2019 at 19:42

IfyouneedaFix's user avatar

Change Sort Order to Language

Check the order, windows default first, your language so English. This solved the problem for me.

answered Dec 18, 2019 at 8:45

Børge Aune's user avatar

1

The language file for VBA editor interface is stored in the following folder with different subfolders:

"C:Program FilesCommon FilesMicrosoft SharedVBAVBA7.1"

You need to search for VBEUIINTL.dll

This folder has around 1033 subfolder and its contents are for English interface. The other ones are for different languages. Sometimes VBA chooses the wrong subfolder. So you basically need to copy the contents of 1033 folder:

"C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033APC71ITL.DLL"
"C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033VBE7INTL.DLL"
"C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033VBEUIINTL.DLL"

to the your current folder for changing the language.

Before you do this, make a back-up first.

answered Sep 26, 2018 at 9:39

jackrider's user avatar

2

I had same issue with VBA editor in German language.
In Excel settings I moved German language to below and English language on up and after restarted was VBA editor in English.

Excel settings — picture

answered Jan 12, 2022 at 13:28

Mike_BossO's user avatar

Решил изучить VBA в Excel для повышения уровня автоматизации работы. Открыл редактор, а он то ли на Китайском, то ли на Корейском языке.

Иероглифы

Русский язык в редактор не завезли, но хотя бы можно включить английский. Для этого нужно закрыть редактор и в ленте нажать «Файл».

Файл

В открывшемся меню нужно нажать «Параметры».

Параметры

Откроется окно «Параметры Excel». В блоке слева нужно выбрать «Язык». Для параметра «Выбор языков редактирования» необходимо выбрать вариант «английский (США)» и нажать кнопку «По умолчанию».

Параметры Excel

Программа выдаст предупреждение. Если вы всё ещё не способны читать иероглифы — нажмите «Да».

Язык редактирования Microsoft Office по умолчанию

Далее в окне «Параметры Excel» нажмите «ОК». Программа выдаст сообщение, что для вступлению изменений в силу требуется перезагрузка. Нажимаем «ОК» и перезапускаем программу.

Изменение языковых параметров Microsoft Office

После повторного запуска программы, вместо иероглифов отобразились слова на английском языке.

Английский язык

Смена раскладки клавиатуры в VBA Excel с РУС на ENG и наоборот с помощью функций Windows API. Автоматическое изменение раскладки в пределах одной таблицы.

Смена раскладки клавиатуры

Поочередная смена раскладки

Для организации поочередной смены раскладки клавиатуры с РУС на ENG и наоборот, имитирующей нажатие сочетания клавиш (Win + Space, Alt + Shift, Ctrl + Shift — в зависимости от ваших настроек), можно использовать функцию Windows API ActivateKeyboardLayout, объявленную в разделе Declarations стандартного модуля:

Declare PtrSafe Function ActivateKeyboardLayout Lib «user32» (ByVal HKL As LongPtr, ByVal flags As LongPtr) As LongPtr

Код VBA Excel для поочередного изменения раскладки клавиатуры:

Sub ToEngOrRus()

Call ActivateKeyboardLayout(0, 0)

End Sub

Заданная смена раскладки

Для смены раскладки клавиатуры из кода VBA Excel с указанием устанавливаемого языка используется функция Windows API LoadKeyboardLayout, объявленная в разделе Declarations стандартного модуля:

Declare PtrSafe Function LoadKeyboardLayout Lib «user32» Alias «LoadKeyboardLayoutA» (ByVal pwszKLID As String, ByVal flags As LongPtr) As LongPtr

Код VBA Excel для изменения раскладки клавиатуры с указанием устанавливаемого языка:

‘Переключение на английскую раскладку

Sub ToEng()

Call LoadKeyboardLayout(«00000409», &H1)

End Sub

‘Переключение на русскую раскладку

Sub ToRus()

Call LoadKeyboardLayout(«00000419», &H1)

End Sub

"00000409" — код английской раскладки;
"00000419" — код русской раскладки.

Определение текущей раскладки

Получить значение текущей раскладки можно с помощью функции Windows API GetKeyboardLayoutName, объявленной в разделе Declarations стандартного модуля:

Declare PtrSafe Function GetKeyboardLayoutName Lib «user32» Alias «GetKeyboardLayoutNameA» (ByVal pwszKLID As String) As LongPtr

Код определения текущей раскладки для вариантов РУС и ENG:

Sub KeyboardLayoutName()

Dim klName As String * 8

GetKeyboardLayoutName klName

    If klName = «00000409» Then

        MsgBox «Текущая раскладка — Английская!»

    ElseIf klName = «00000419» Then

        MsgBox «Текущая раскладка — Русская!»

    Else

        MsgBox «Текущая раскладка — не Русская и не Английская!»

    End If

End Sub

Переменная klName объявлена как строка фиксированной длины. Запуск процедуры с обычной переменной может вызывать ошибку, закрывающую приложение. Так происходит в моей версии Excel 2016.

Смена раскладки в таблице

Автоматическое изменение раскладки в пределах одной таблицы при переходе между ячейками.

Для автоматической смены раскладки при переходе между ячейками разных диапазонов одного рабочего листа будем использовать функцию Windows API LoadKeyboardLayout, объявленную в разделе Declarations стандартного модуля:

Declare PtrSafe Function LoadKeyboardLayout Lib «user32» Alias «LoadKeyboardLayoutA» (ByVal pwszKLID As String, ByVal flags As LongPtr) As LongPtr

Допустим, что в 5 и 7 столбцах нашей таблицы находятся данные на английском языке или, попросту, требующие ввод латиницей. Чтобы не переключать каждый раз раскладку клавиатуры вручную, разместим в модуле нужного листа следующий код VBA Excel:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Select Case Target.Column

        Case 5, 7

            Call Module3.LoadKeyboardLayout(«00000409», &H1)

        Case Else:

            Call Module3.LoadKeyboardLayout(«00000419», &H1)

    End Select

End Sub

Теперь при переходе к ячейкам 5 и 7 столбцов раскладка клавиатуры автоматически меняется на ENG, а при уходе с них — на РУС.

Module3 — это стандартный модуль, в котором размещена функция Windows API LoadKeyboardLayout.


1 / 1 / 0

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

Сообщений: 4

1

03.08.2016, 13:49. Показов 29094. Ответов 9


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

Здравствуйте, подскажите, где меняется язык интерфейса VBA? Вместо английского меню отображаются иероглифы

Миниатюры

Поменять язык интерфейса VBA
 



0



190 / 59 / 20

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

Сообщений: 234

03.08.2016, 13:56

2

В самом экселе попробуйте посмотреть

Миниатюры

Поменять язык интерфейса VBA
 



0



1 / 1 / 0

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

Сообщений: 4

03.08.2016, 14:18

 [ТС]

3

спасибо, языки указаны верно. проблема появилась после установки VBA для автокада, в актокаде меню отображается нормально, в word и excel -иероглифы

Миниатюры

Поменять язык интерфейса VBA
 



1



2 / 2 / 0

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

Сообщений: 1

14.11.2016, 12:44

4

Меняем язык, перезапускаем Excel..

Миниатюры

Поменять язык интерфейса VBA
 



2



1 / 1 / 0

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

Сообщений: 1

26.03.2017, 17:42

5

Большое спасибо!!! Помогло!



1



0 / 0 / 0

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

Сообщений: 1

06.11.2020, 22:08

6

Большое спасибо



0



0 / 0 / 0

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

Сообщений: 14

16.02.2021, 11:52

7

А руссифицировать можно как нибудь?



0



0 / 0 / 0

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

Сообщений: 1

21.06.2021, 09:58

8

К сожалению не помогло. Может не хватает шрифтов?



0



ᴁ®

Эксперт MS Access

3069 / 1735 / 361

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

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

Записей в блоге: 4

21.06.2021, 11:31

9

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

К сожалению не помогло. Может не хватает шрифтов?

Тема 16 года. Если у вас проблема, создайте новую тему с описанием. (тоже автокад устанавливали?)
Но для начала откатите шрифты



0



0 / 0 / 0

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

Сообщений: 1

08.09.2022, 12:06

10

Мне помогло!
Смена «Языки разработки и проверка..» на английский переключил — вместо иероглифов в VBA стал норм английский.

Миниатюры

Поменять язык интерфейса VBA
 



0



После обновления Microsoft Office до версии 2016 года я обнаружил, что интерфейс VBA на немецком языке. Как мне восстановить его на английский?

В моих настройках Windows 10 установлен английский язык, и все локальные настройки также соответствуют английскому языку Великобритании (даты, десятичные дроби и т. Д.).

Я установил в качестве предпочтительного языка Office английский.

Please find screen-shot attached

7 ответов

У меня была та же проблема, за исключением того, что интерфейс моего VBA был французским.
Windows 8.1 и Office 2013 были установлены с венгерским языком, региональные настройки и параметры «не-юникод» также установлены на венгерский.

У меня есть 3 папки в C:Program Files (x86)Common FilesMicrosoft SharedVBAVBA7.1:
— 1033 — английский (США)
— 1036 — французский
— 1038 — Венгерский
Источник кодов языков: renenyffenegger.ch.

К сожалению, у меня нет прав администратора, поэтому я не мог изменять файлы или папки внутри Program Files (x86).
Я не понимаю, как это сделать, но я могу изменить HKEY_CURRENT_USER в реестре (regedit.exe).

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

Прежде всего, вам нужно закрыть все приложения Office.

№1
В HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0CommonLanguageResources больше значений REG_MULTI_SZ с такими данными, как 0;1038;1033;1036.

Удалите ненужный языковой код отовсюду. (1031 — немецкий, 1036 — французский и т. Д., См. Ссылку выше)
Я удалил 1036, в результате чего: 0;1038;1033

Они будут автоматически восстановлены после запуска Excel, но не беспокойтесь об этом.

№2
В HKEY_CURRENT_USERSoftwareMicrosoftOffice15.0CommonLanguageResourcesEnabledLanguages установите нежелательный языковой код с ExplicitOn на Off или On.

Неважно, что вы установили, потому что после следующего запуска Excel автоматически будет установлено значение On.

В моем случае одно или оба из них были решением, и язык интерфейса VBA, наконец, английский.


1

Vikitorony
9 Апр 2019 в 15:47

Это сработало для меня (пользователь Windows 10).

Все настройки> Время и язык> Регион и язык.

В разделе «Предпочитаемые языки» добавьте язык, который вы хотите использовать. Если этот язык уже есть в списке, убедитесь, что он находится вверху (вы можете переместить его, щелкнув по нему один раз и используя стрелки вверх / вниз слева).

Вы заметите комментарий под заголовком, который гласит: «Приложения и языки будут отображаться на первом языке, который они поддерживают». В моем случае основным языком был норвежский, а следующим в списке был китайский. VBA по какой-то причине не распознал норвежский язык и предположил, что китайский язык будет лучшим вариантом. Я установил английский (США), переместил его в начало списка и перезагрузил компьютер. Бум.


1

IfyouneedaFix
8 Июл 2019 в 22:42

Изменить порядок сортировки на язык

Проверьте порядок, сначала Windows по умолчанию, ваш язык, значит английский. Это решило проблему для меня.


1

Børge Aune
18 Дек 2019 в 11:45

Языковой файл для интерфейса редактора VBA хранится в следующей папке с разными подпапками:

"C:Program FilesCommon FilesMicrosoft SharedVBAVBA7.1"

Вам нужно найти VBEUIINTL.dll

В этой папке около 1033 подпапок, и ее содержимое предназначено для английского интерфейса. Остальные — для разных языков. Иногда VBA выбирает неправильную подпапку. Итак, вам в основном нужно скопировать содержимое папки 1033:

"C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033APC71ITL.DLL"
"C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033VBE7INTL.DLL"
"C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.11033VBEUIINTL.DLL"

В текущую папку для изменения языка.

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


0

jackrider
26 Сен 2018 в 12:39

Я пробовал вышеуказанные решения и не работал у меня. Этот работает и не требует прав администратора.

Закройте все приложения Office. Откройте любое приложение Office, например. Excel

Выберите: Параметры, Язык

Выберите язык по умолчанию для выпуска: английский (этот вариант, вероятно, не является обязательным, но я сделал это, когда искал решение) Установите английский из списка заказов как верхний язык для отображения Установите английский из списка заказов как верхний язык для справки

Похоже, что язык VBA основан на этих двух вариантах и ​​выбирается по порядку.
Мой основной язык — польский, а мой редактор VBA был на итальянском.
Чтобы изменить язык VBA на английский, я установил порядок из этих списков, чтобы английский был выбран в качестве первого языка, если что-то не может отображаться на польском языке. (ранее итальянский был под номером 3 в этом списке)
Настройка языка VBA


3

Robert de Clair
23 Авг 2020 в 17:25

Взгляните на настройку на Control Panel > Region and Language > Administrative. Если он показывает «Германия / Немецкий» для программ, отличных от Unicode, вы можете изменить его там.


Эта ветка на сайте answers.microsoft.com предлагает взглянуть на папку C:Program FilesCommon Filesmicrosoft sharedVBAVBA7.1.

Здравствуйте, у меня была такая же проблема, и я наконец нашел решение. Языковой файл для интерфейса редактора VBA хранится в следующей папке с разными подпапками:

C: Program Files Common Files Microsoft общий VBA VBA7.1

(вам может потребоваться поиск VBEUIINTL.dll, если вы не можете найти эту папку на своем компьютере)

в этой папке подпапка 1033 и ее содержимое предназначены для английского интерфейса. Остальные — для разных языков. Каким-то образом VBA выбирает неправильную подпапку. Таким образом, вам в основном нужно скопировать содержимое папки 1033 (в качестве обходного пути):

«C: Program Files Common Files microsoft shared VBA VBA7.1 1033 APC71ITL.DLL»
«C: Program Files Common Files microsoft shared VBA VBA7.1 1033 VBE7INTL.DLL»
«C: Program Files Common Files microsoft shared VBA VBA7.1 1033 VBEUIINTL.DLL»

в папку 2052 (для китайского например может быть у вас другой), для смены языка.

Перед этим перезапустите и не запускайте никакие офисные продукты. Затем скопируйте файлы; перезаписать, если спросят. Я также предлагаю вам сделать резервную копию папки VBA7.1 на случай, если что-то пойдет не так.

Предложение о перезагрузке кажется мне немного ненужным — просто убедитесь, что все офисные программы, поддерживающие VBA (Excel, Word, Access, PowerPoint, Outlook), закрыты.

Кроме того, этот последний метод больше похож на лечение симптомов — мне кажется, что это неправильный способ изменения языка вашего VBE (всего лишь один неоптимальный способ).


1

Inarion
26 Сен 2018 в 12:34

У меня была такая же проблема с редактором VBA на немецком языке. В настройках Excel я переместил немецкий язык ниже, а английский язык вверх, и после перезапуска редактор VBA был на английском языке.

Настройки Excel — картинка


0

Mike_BossO
12 Янв 2022 в 16:28

Как изменить английский на русский язык VBA

xuk

Дата: Пятница, 27.01.2012, 14:19 |
Сообщение № 1

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

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

Сообщений: 41


Репутация:

0

±

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


Добрый день!
Помогите пожалуйста разобраться, в Excel есть выход на visual basic но он на английском языке.
Вопрос: можно ли как то настроить на русский или переключиться на visual basic studio 8?

 

Ответить

Serge_007

Дата: Пятница, 27.01.2012, 14:32 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 15894


Репутация:

2623

±

Замечаний:
±


Excel 2016

Quote (xuk)

можно ли как то настроить на русский

Нет.


ЮMoney:41001419691823 | WMR:126292472390

 

Ответить

xuk

Дата: Пятница, 27.01.2012, 14:39 |
Сообщение № 3

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

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

Сообщений: 41


Репутация:

0

±

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


Я понял так, что нельзя и переключится на visual basic studio и настоить на русский язык

 

Ответить

Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic

Introduction

This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).

Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.

  • In 1996, there were over 30 million users of Microsoft Excel (source).
  • Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.

We’re one big happy family!

In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.

Prerequisites

You don’t need any prior programming experience to understand this tutorial. However, you will need:

  • Basic to intermediate familiarity with Microsoft Excel
  • If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
  • A willingness to try new things

Learning Objectives

Over the course of this article, you will learn:

  1. What VBA is
  2. Why you would use VBA
  3. How to get set up in Excel to write VBA
  4. How to solve some real-world problems with VBA

Important Concepts

Here are some important concepts that you should be familiar with to fully understand this tutorial.

Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.

If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!

Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:

  • Subroutines: a group of VBA statements that performs one or more actions
  • Functions: a group of VBA statements that performs one or more actions and returns one or more values

Note: you can have functions operating inside of subroutines. You’ll see later.

Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.

Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.

For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.

What is VBA?

Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.

Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.

But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.

Pizza in a pizza oven

Yum.

Why use VBA in Excel?

Because wood-fired pizza is the best!

But seriously.

A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?

Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.

You should consider using VBA if you need to:

  • Automate repetitive tasks
  • Create easy ways for users to interact with your spreadsheets
  • Manipulate large amounts of data

Getting Set Up to Write VBA in Excel

Developer Tab

To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.

VBA developer tab

To add the Developer tab to the ribbon:

  1. On the File tab, go to Options > Customize Ribbon.
  2. Under Customize the Ribbon and under Main Tabs, select the Developer check box.

After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.

VBA Editor

Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.

VBA editor

Excel VBA Examples

First, let’s create a file for us to play around in.

  1. Open a new Excel file
  2. Save it as a macro-enabled workbook (. xlsm)
  3. Select the Developer tab
  4. Open the VBA Editor

Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.

Example #1: Display a Message when Users Open the Excel Workbook

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub

Save, close the workbook, and reopen the workbook. This dialog should display.

Welcome to XYZ notebook message example

Ta da!

How is it doing that?

Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:

  • Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
  • Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
  • By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
  • msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”

In short, this is a simple subroutine that contains a function.

When could I use this?

Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.

  • Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
  • Solution: create a user message that contains a concise answer to each of these frequently answered questions.

Real World Examples

  • Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
  • Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
  • Use the InputBox function to get information from the user

Example #2: Allow User to Execute another Procedure

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub

Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub

Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.

Now click the button. This message should display:

Process the XYZ report message example

Click “yes” or hit Enter.

Thanks for processing the XYZ report message example

Once again, tada!

Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first…

How is it doing that?

This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:

  • Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
  • Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
  • UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
  • Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
  • If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.

When could I use this?

This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.

For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.

  • Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
  • Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.

Real World Examples

  • Create a dialog box for user to automatically populate certain information across multiple sheets
  • Use the InputBox function to get information from the user, which is then populated across multiple sheets

Example #3: Add Numbers to a Range with a For-Next Loop

For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub

Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.

This should happen:

For-Next loop results

Etc, until the 100th row.

How is it doing that?

  • Dim X As Integer: declares the variable X as a data type of Integer.
  • For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
  • Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
  • Next X: this tells the loop to run again

When could I use this?

The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.

Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.

You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.

Real World Examples

  • Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
  • Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
  • Loop through each character in a string and extract all numbers
  • Randomly select a number of values from an array

Conclusion

Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.

  • What is VBA?
  • How do I get set up to start using VBA in Excel?
  • Why and when would you use VBA?
  • What are some problems I could solve with VBA?

If you have a fair idea of how to you could answer these questions, then this was successful.

Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.

Happy coding!

Learning Resources

  • Excel VBA Programming for Dummies, John Walkenbach
  • Get Started with VBA, Microsoft Documentation
  • Learning VBA in Excel, Lynda

A bit about me

I’m Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I’m continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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