Время на прочтение
7 мин
Количество просмотров 312K
Приветствую всех.
В этом посте я расскажу, что такое VBA и как с ним работать в Microsoft Excel 2007/2010 (для более старых версий изменяется лишь интерфейс — код, скорее всего, будет таким же) для автоматизации различной рутины.
VBA (Visual Basic for Applications) — это упрощенная версия Visual Basic, встроенная в множество продуктов линейки Microsoft Office. Она позволяет писать программы прямо в файле конкретного документа. Вам не требуется устанавливать различные IDE — всё, включая отладчик, уже есть в Excel.
Еще при помощи Visual Studio Tools for Office можно писать макросы на C# и также встраивать их. Спасибо, FireStorm.
Сразу скажу — писать на других языках (C++/Delphi/PHP) также возможно, но требуется научится читать, изменять и писать файлы офиса — встраивать в документы не получится. А интерфейсы Microsoft работают через COM. Чтобы вы поняли весь ужас, вот Hello World с использованием COM.
Поэтому, увы, будем учить Visual Basic.
Чуть-чуть подготовки и постановка задачи
Итак, поехали. Открываем Excel.
Для начала давайте добавим в Ribbon панель «Разработчик». В ней находятся кнопки, текстовые поля и пр. элементы для конструирования форм.
Появилась вкладка.
Теперь давайте подумаем, на каком примере мы будем изучать VBA. Недавно мне потребовалось красиво оформить прайс-лист, выглядевший, как таблица. Идём в гугл, набираем «прайс-лист» и качаем любой, который оформлен примерно так (не сочтите за рекламу, пожалуйста):
То есть требуется, чтобы было как минимум две группы, по которым можно объединить товары (в нашем случае это будут Тип и Производитель — в таком порядке). Для того, чтобы предложенный мною алгоритм работал корректно, отсортируйте товары так, чтобы товары из одной группы стояли подряд (сначала по Типу, потом по Производителю).
Результат, которого хотим добиться, выглядит примерно так:
Разумеется, если смотреть прайс только на компьютере, то можно добавить фильтры и будет гораздо удобнее искать нужный товар. Однако мы хотим научится кодить и задача вполне подходящая, не так ли?
Кодим
Для начала требуется создать кнопку, при нажатии на которую будет вызываться наша програма. Кнопки находятся в панели «Разработчик» и появляются по кнопке «Вставить». Вам нужен компонент формы «Кнопка». Нажали, поставили на любое место в листе. Далее, если не появилось окно назначения макроса, надо нажать правой кнопкой и выбрать пункт «Назначить макрос». Назовём его FormatPrice. Важно, чтобы перед именем макроса ничего не было — иначе он создастся в отдельном модуле, а не в пространстве имен книги. В этому случае вам будет недоступно быстрое обращение к выделенному листу. Нажимаем кнопку «Новый».
И вот мы в среде разработки VB. Также её можно вызвать из контекстного меню командой «Исходный текст»/«View code».
Перед вами окно с заглушкой процедуры. Можете его развернуть. Код должен выглядеть примерно так:
Sub FormatPrice()End Sub
Напишем Hello World:
Sub FormatPrice()
MsgBox "Hello World!"
End Sub
И запустим либо щелкнув по кнопке (предварительно сняв с неё выделение), либо клавишей F5 прямо из редактора.
Тут, пожалуй, следует отвлечься на небольшой ликбез по поводу синтаксиса VB. Кто его знает — может смело пропустить этот раздел до конца. Основное отличие Visual Basic от Pascal/C/Java в том, что команды разделяются не ;, а переносом строки или двоеточием (:), если очень хочется написать несколько команд в одну строку. Чтобы понять основные правила синтаксиса, приведу абстрактный код.
Примеры синтаксиса
' Процедура. Ничего не возвращает
' Перегрузка в VBA отсутствует
Sub foo(a As String, b As String)
' Exit Sub ' Это значит "выйти из процедуры"
MsgBox a + ";" + b
End Sub' Функция. Вовращает Integer
Function LengthSqr(x As Integer, y As Integer) As Integer
' Exit Function
LengthSqr = x * x + y * y
End FunctionSub FormatPrice()
Dim s1 As String, s2 As String
s1 = "str1"
s2 = "str2"
If s1 <> s2 Then
foo "123", "456" ' Скобки при вызове процедур запрещены
End IfDim res As sTRING ' Регистр в VB не важен. Впрочем, редактор Вас поправит
Dim i As Integer
' Цикл всегда состоит из нескольких строк
For i = 1 To 10
res = res + CStr(i) ' Конвертация чего угодно в String
If i = 5 Then Exit For
Next iDim x As Double
x = Val("1.234") ' Парсинг чисел
x = x + 10
MsgBox xOn Error Resume Next ' Обработка ошибок - игнорировать все ошибки
x = 5 / 0
MsgBox xOn Error GoTo Err ' При ошибке перейти к метке Err
x = 5 / 0
MsgBox "OK!"
GoTo ne
Err:
MsgBox
"Err!"
ne:
On Error GoTo 0 ' Отключаем обработку ошибок
' Циклы бывает, какие захотите
Do While True
Exit DoLoop 'While True
Do 'Until False
Exit Do
Loop Until False
' А вот при вызове функций, от которых хотим получить значение, скобки нужны.
' Val также умеет возвращать Integer
Select Case LengthSqr(Len("abc"), Val("4"))
Case 24
MsgBox "0"
Case 25
MsgBox "1"
Case 26
MsgBox "2"
End Select' Двухмерный массив.
' Можно также менять размеры командой ReDim (Preserve) - см. google
Dim arr(1 to 10, 5 to 6) As Integer
arr(1, 6) = 8Dim coll As New Collection
Dim coll2 As Collection
coll.Add "item", "key"
Set coll2 = coll ' Все присваивания объектов должны производится командой Set
MsgBox coll2("key")
Set coll2 = New Collection
MsgBox coll2.Count
End Sub
Грабли-1. При копировании кода из IDE (в английском Excel) есь текст конвертируется в 1252 Latin-1. Поэтому, если хотите сохранить русские комментарии — надо сохранить крокозябры как Latin-1, а потом открыть в 1251.
Грабли-2. Т.к. VB позволяет использовать необъявленные переменные, я всегда в начале кода (перед всеми процедурами) ставлю строчку Option Explicit. Эта директива запрещает интерпретатору заводить переменные самостоятельно.
Грабли-3. Глобальные переменные можно объявлять только до первой функции/процедуры. Локальные — в любом месте процедуры/функции.
Еще немного дополнительных функций, которые могут пригодится: InPos, Mid, Trim, LBound, UBound. Также ответы на все вопросы по поводу работы функций/их параметров можно получить в MSDN.
Надеюсь, что этого Вам хватит, чтобы не пугаться кода и самостоятельно написать какое-нибудь домашнее задание по информатике. По ходу поста я буду ненавязчиво знакомить Вас с новыми конструкциями.
Кодим много и под Excel
В этой части мы уже начнём кодить нечто, что умеет работать с нашими листами в Excel. Для начала создадим отдельный лист с именем result (лист с данными назовём data). Теперь, наверное, нужно этот лист очистить от того, что на нём есть. Также мы «выделим» лист с данными, чтобы каждый раз не писать длинное обращение к массиву с листами.
Sub FormatPrice()
Sheets("result").Cells.Clear
Sheets("data").Activate
End Sub
Работа с диапазонами ячеек
Вся работа в Excel VBA производится с диапазонами ячеек. Они создаются функцией Range и возвращают объект типа Range. У него есть всё необходимое для работы с данными и/или оформлением. Кстати сказать, свойство Cells листа — это тоже Range.
Примеры работы с Range
Sheets("result").Activate
Dim r As Range
Set r = Range("A1")
r.Value = "123"
Set r = Range("A3,A5")
r.Font.Color = vbRed
r.Value = "456"
Set r = Range("A6:A7")
r.Value = "=A1+A3"
Теперь давайте поймем алгоритм работы нашего кода. Итак, у каждой строчки листа data, начиная со второй, есть некоторые данные, которые нас не интересуют (ID, название и цена) и есть две вложенные группы, к которым она принадлежит (тип и производитель). Более того, эти строки отсортированы. Пока мы забудем про пропуски перед началом новой группы — так будет проще. Я предлагаю такой алгоритм:
- Считали группы из очередной строки.
- Пробегаемся по всем группам в порядке приоритета (вначале более крупные)
- Если текущая группа не совпадает, вызываем процедуру AddGroup(i, name), где i — номер группы (от номера текущей до максимума), name — её имя. Несколько вызовов необходимы, чтобы создать не только наш заголовок, но и всё более мелкие.
- После отрисовки всех необходимых заголовков делаем еще одну строку и заполняем её данными.
Для упрощения работы рекомендую определить следующие функции-сокращения:
Function GetCol(Col As Integer) As String
GetCol = Chr(Asc("A") + Col)
End FunctionFunction GetCellS(Sheet As String, Col As Integer, Row As Integer) As Range
Set GetCellS = Sheets(Sheet).Range(GetCol(Col) + CStr(Row))
End FunctionFunction GetCell(Col As Integer, Row As Integer) As Range
Set GetCell = Range(GetCol(Col) + CStr(Row))
End Function
Далее определим глобальную переменную «текущая строчка»: Dim CurRow As Integer. В начале процедуры её следует сделать равной единице. Еще нам потребуется переменная-«текущая строка в data», массив с именами групп текущей предыдущей строк. Потом можно написать цикл «пока первая ячейка в строке непуста».
Глобальные переменные
Option Explicit ' про эту строчку я уже рассказывал
Dim CurRow As Integer
Const GroupsCount As Integer = 2
Const DataCount As Integer = 3
FormatPrice
Sub FormatPrice()
Dim I As Integer ' строка в data
CurRow = 1
Dim Groups(1 To GroupsCount) As String
Dim PrGroups(1 To GroupsCount) As String
Sheets(
"data").Activate
I = 2
Do While True
If GetCell(0, I).Value = "" Then Exit Do
' ...
I = I + 1
Loop
End Sub
Теперь надо заполнить массив Groups:
На месте многоточия
Dim I2 As Integer
For I2 = 1 To GroupsCount
Groups(I2) = GetCell(I2, I)
Next I2
' ...
For I2 = 1 To GroupsCount ' VB не умеет копировать массивы
PrGroups(I2) = Groups(I2)
Next I2
I = I + 1
И создать заголовки:
На месте многоточия в предыдущем куске
For I2 = 1 To GroupsCount
If Groups(I2) <> PrGroups(I2) Then
Dim I3 As Integer
For I3 = I2 To GroupsCount
AddHeader I3, Groups(I3)
Next I3
Exit For
End If
Next I2
Не забудем про процедуру AddHeader:
Перед FormatPrice
Sub AddHeader(Ty As Integer, Name As String)
GetCellS("result", 1, CurRow).Value = Name
CurRow = CurRow + 1
End Sub
Теперь надо перенести всякую информацию в result
For I2 = 0 To DataCount - 1
GetCellS("result", I2, CurRow).Value = GetCell(I2, I)
Next I2
Подогнать столбцы по ширине и выбрать лист result для показа результата
После цикла в конце FormatPrice
Sheets("Result").Activate
Columns.AutoFit
Всё. Можно любоваться первой версией.
Некрасиво, но похоже. Давайте разбираться с форматированием. Сначала изменим процедуру AddHeader:
Sub AddHeader(Ty As Integer, Name As String)
Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow)).Merge
' Чтобы не заводить переменную и не писать каждый раз длинный вызов
' можно воспользоваться блоком With
With GetCellS("result", 0, CurRow)
.Value = Name
.Font.Italic = True
.Font.Name = "Cambria"
Select Case Ty
Case 1 ' Тип
.Font.Bold = True
.Font.Size = 16
Case 2 ' Производитель
.Font.Size = 12
End Select
.HorizontalAlignment = xlCenter
End With
CurRow = CurRow + 1
End Sub
Уже лучше:
Осталось только сделать границы. Тут уже нам требуется работать со всеми объединёнными ячейками, иначе бордюр будет только у одной:
Поэтому чуть-чуть меняем код с добавлением стиля границ:
Sub AddHeader(Ty As Integer, Name As String)
With Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow))
.Merge
.Value = Name
.Font.Italic = True
.Font.Name = "Cambria"
.HorizontalAlignment = xlCenterSelect Case Ty
Case 1 ' Тип
.Font.Bold = True
.Font.Size = 16
.Borders(xlTop).Weight = xlThick
Case 2 ' Производитель
.Font.Size = 12
.Borders(xlTop).Weight = xlMedium
End Select
.Borders(xlBottom).Weight = xlMedium ' По убыванию: xlThick, xlMedium, xlThin, xlHairline
End With
CurRow = CurRow + 1
End Sub
Осталось лишь добится пропусков перед началом новой группы. Это легко:
В начале FormatPrice
Dim I As Integer ' строка в data
CurRow = 0 ' чтобы не было пропуска в самом начале
Dim Groups(1 To GroupsCount) As String
В цикле расстановки заголовков
If Groups(I2) <> PrGroups(I2) Then
CurRow = CurRow + 1
Dim I3 As Integer
В точности то, что и хотели.
Надеюсь, что эта статья помогла вам немного освоится с программированием для Excel на VBA. Домашнее задание — добавить заголовки «ID, Название, Цена» в результат. Подсказка: CurRow = 0 CurRow = 1.
Файл можно скачать тут (min.us) или тут (Dropbox). Не забудьте разрешить исполнение макросов. Если кто-нибудь подскажет человеческих файлохостинг, залью туда.
Спасибо за внимание.
Буду рад конструктивной критике в комментариях.
UPD: Перезалил пример на Dropbox и min.us.
UPD2: На самом деле, при вызове процедуры с одним параметром скобки можно поставить. Либо использовать конструкцию Call Foo(«bar», 1, 2, 3) — тут скобки нужны постоянно.
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:
- What VBA is
- Why you would use VBA
- How to get set up in Excel to write VBA
- 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.
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.
To add the Developer tab to the ribbon:
- On the File tab, go to Options > Customize Ribbon.
- 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.
Excel VBA Examples
First, let’s create a file for us to play around in.
- Open a new Excel file
- Save it as a macro-enabled workbook (. xlsm)
- Select the Developer tab
- 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.
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:
Click “yes” or hit Enter.
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:
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 — Overview
VBA stands for Visual Basic for Applications an event-driven programming language from Microsoft that is now predominantly used with Microsoft office applications such as MSExcel, MS-Word, and MS-Access.
It helps techies to build customized applications and solutions to enhance the capabilities of those applications. The advantage of this facility is that you NEED NOT have visual basic installed on our PC, however, installing Office will implicitly help in achieving the purpose.
You can use VBA in all office versions, right from MS-Office 97 to MS-Office 2013 and also with any of the latest versions available. Among VBA, Excel VBA is the most popular. The advantage of using VBA is that you can build very powerful tools in MS Excel using linear programming.
Application of VBA
You might wonder why to use VBA in Excel as MS-Excel itself provides loads of inbuilt functions. MS-Excel provides only basic inbuilt functions which might not be sufficient to perform complex calculations. Under such circumstances, VBA becomes the most obvious solution.
For example, it is very hard to calculate the monthly repayment of a loan using Excel’s built-in formulas. Rather, it is easy to program a VBA for such a calculation.
Accessing VBA Editor
In Excel window, press «ALT+F11». A VBA window opens up as shown in the following screenshot.
VBA — Excel Macros
In this chapter, you will learn how to write a simple macro in a step by step manner.
Step 1 − First, enable ‘Developer’ menu in Excel 20XX. To do the same, click File → Options.
Step 2 − Click ‘Customize the Ribbon’ tab and check ‘Developer’. Click ‘OK’.
Step 3 − The ‘Developer’ ribbon appears in the menu bar.
Step 4 − Click the ‘Visual Basic’ button to open the VBA Editor.
Step 5 − Start scripting by adding a button. Click Insert → Select the button.
Step 6 − Perform a right-click and choose ‘properties’.
Step 7 − Edit the name and caption as shown in the following screenshot.
Step 8 − Now double-click the button and the sub-procedure outline will be displayed as shown in the following screenshot.
Step 9 − Start coding by simply adding a message.
Private Sub say_helloworld_Click() MsgBox "Hi" End Sub
Step 10 − Click the button to execute the sub-procedure. The output of the sub-procedure is shown in the following screenshot. Make sure that you do have design mode turned on. Simply click it to turn it on if it is not on.
Note − In further chapters, we will demonstrate using a simple button, as explained from step#1 to 10. Hence , it is important to understand this chapter thoroughly.
VBA — Excel Terms
In this chapter, you will acquaint yourself with the commonly used excel VBA terminologies. These terminologies will be used in further modules, hence understanding each one of these is important.
Modules
Modules is the area where the code is written. This is a new Workbook, hence there aren’t any Modules.
To insert a Module, navigate to Insert → Module. Once a module is inserted ‘module1’ is created.
Within the modules, we can write VBA code and the code is written within a Procedure. A Procedure/Sub Procedure is a series of VBA statements instructing what to do.
Procedure
Procedures are a group of statements executed as a whole, which instructs Excel how to perform a specific task. The task performed can be a very simple or a very complicated task. However, it is a good practice to break down complicated procedures into smaller ones.
The two main types of Procedures are Sub and Function.
Function
A function is a group of reusable code, which can be called anywhere in your program. This eliminates the need of writing the same code over and over again. This helps the programmers to divide a big program into a number of small and manageable functions.
Apart from inbuilt Functions, VBA allows to write user-defined functions as well and statements are written between Function and End Function.
Sub-Procedures
Sub-procedures work similar to functions. While sub procedures DO NOT Return a value, functions may or may not return a value. Sub procedures CAN be called without call keyword. Sub procedures are always enclosed within Sub and End Sub statements.
VBA — Macro Comments
Comments are used to document the program logic and the user information with which other programmers can seamlessly work on the same code in future.
It includes information such as developed by, modified by, and can also include incorporated logic. Comments are ignored by the interpreter while execution.
Comments in VBA are denoted by two methods.
-
Any statement that starts with a Single Quote (‘) is treated as comment. Following is an example.
' This Script is invoked after successful login ' Written by : TutorialsPoint ' Return Value : True / False
-
Any statement that starts with the keyword «REM». Following is an example.
REM This Script is written to Validate the Entered Input REM Modified by : Tutorials point/user2
VBA — Message Box
The MsgBox function displays a message box and waits for the user to click a button and then an action is performed based on the button clicked by the user.
Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])
Parameter Description
-
Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line.
-
Buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0.
-
Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar.
-
Helpfile − An Optional Parameter. A String expression that identifies the Help file to use for providing context-sensitive help for the dialog box.
-
Context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided.
The Buttons parameter can take any of the following values −
-
0 vbOKOnly — Displays OK button only.
-
1 vbOKCancel — Displays OK and Cancel buttons.
-
2 vbAbortRetryIgnore — Displays Abort, Retry, and Ignore buttons.
-
3 vbYesNoCancel — Displays Yes, No, and Cancel buttons.
-
4 vbYesNo — Displays Yes and No buttons.
-
5 vbRetryCancel — Displays Retry and Cancel buttons.
-
16 vbCritical — Displays Critical Message icon.
-
32 vbQuestion — Displays Warning Query icon.
-
48 vbExclamation — Displays Warning Message icon.
-
64 vbInformation — Displays Information Message icon.
-
0 vbDefaultButton1 — First button is default.
-
256 vbDefaultButton2 — Second button is default.
-
512 vbDefaultButton3 — Third button is default.
-
768 vbDefaultButton4 — Fourth button is default.
-
0 vbApplicationModal Application modal — The current application will not work until the user responds to the message box.
-
4096 vbSystemModal System modal — All applications will not work until the user responds to the message box.
The above values are logically divided into four groups: The first group (0 to 5) indicates the buttons to be displayed in the message box. The second group (16, 32, 48, 64) describes the style of the icon to be displayed, the third group (0, 256, 512, 768) indicates which button must be the default, and the fourth group (0, 4096) determines the modality of the message box.
Return Values
The MsgBox function can return one of the following values which can be used to identify the button the user has clicked in the message box.
- 1 — vbOK — OK was clicked
- 2 — vbCancel — Cancel was clicked
- 3 — vbAbort — Abort was clicked
- 4 — vbRetry — Retry was clicked
- 5 — vbIgnore — Ignore was clicked
- 6 — vbYes — Yes was clicked
- 7 — vbNo — No was clicked
Example
Function MessageBox_Demo() 'Message Box with just prompt message MsgBox("Welcome") 'Message Box with title, yes no and cancel Butttons int a = MsgBox("Do you like blue color?",3,"Choose options") ' Assume that you press No Button msgbox ("The Value of a is " & a) End Function
Output
Step 1 − The above Function can be executed either by clicking the «Run» button on VBA Window or by calling the function from Excel Worksheet as shown in the following screenshot.
Step 2 − A Simple Message box is displayed with a message «Welcome» and an «OK» Button
Step 3 − After Clicking OK, yet another dialog box is displayed with a message along with «yes, no, and cancel» buttons.
Step 4 − After clicking the ‘No’ button, the value of that button (7) is stored as an integer and displayed as a message box to the user as shown in the following screenshot. Using this value, it can be understood which button the user has clicked.
VBA — InputBox
The InputBox function prompts the users to enter values. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks the Cancel button, the function will return an empty string («»).
Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
Parameter Description
-
Prompt − A required parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then the lines can be separated using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line.
-
Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar.
-
Default − An optional parameter. A default text in the text box that the user would like to be displayed.
-
XPos − An optional parameter. The position of X axis represents the prompt distance from the left side of the screen horizontally. If left blank, the input box is horizontally centered.
-
YPos − An optional parameter. The position of Y axis represents the prompt distance from the left side of the screen vertically. If left blank, the input box is vertically centered.
-
Helpfile − An optional parameter. A String expression that identifies the helpfile to be used to provide context-sensitive Help for the dialog box.
-
context − An optional parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided.
Example
Let us calculate the area of a rectangle by getting values from the user at run time with the help of two input boxes (one for length and one for width).
Function findArea() Dim Length As Double Dim Width As Double Length = InputBox("Enter Length ", "Enter a Number") Width = InputBox("Enter Width", "Enter a Number") findArea = Length * Width End Function
Output
Step 1 − To execute the same, call using the function name and press Enter as shown in the following screenshot.
Step 2 − Upon execution, the First input box (length) is displayed. Enter a value into the input box.
Step 3 − After entering the first value, the second input box (width) is displayed.
Step 4 − Upon entering the second number, click the OK button. The area is displayed as shown in the following screenshot.
VBA — Variables
Variable is a named memory location used to hold a value that can be changed during the script execution. Following are the basic rules for naming a variable.
-
You must use a letter as the first character.
-
You can’t use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name.
-
Name can’t exceed 255 characters in length.
-
You cannot use Visual Basic reserved keywords as variable name.
Syntax
In VBA, you need to declare the variables before using them.
Dim <<variable_name>> As <<variable_type>>
Data Types
There are many VBA data types, which can be divided into two main categories, namely numeric and non-numeric data types.
Numeric Data Types
Following table displays the numeric data types and the allowed range of values.
Type | Range of Values |
---|---|
Byte | 0 to 255 |
Integer | -32,768 to 32,767 |
Long | -2,147,483,648 to 2,147,483,648 |
Single |
-3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E+38 for positive values. |
Double |
-1.79769313486232e+308 to -4.94065645841247E-324 for negative values 4.94065645841247E-324 to 1.79769313486232e+308 for positive values. |
Currency | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 |
Decimal |
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use +/- 7.9228162514264337593543950335 (28 decimal places). |
Non-Numeric Data Types
Following table displays the non-numeric data types and the allowed range of values.
Type | Range of Values |
---|---|
String (fixed length) | 1 to 65,400 characters |
String (variable length) | 0 to 2 billion characters |
Date | January 1, 100 to December 31, 9999 |
Boolean | True or False |
Object | Any embedded object |
Variant (numeric) | Any value as large as double |
Variant (text) | Same as variable-length string |
Example
Let us create a button and name it as ‘Variables_demo’ to demonstrate the use of variables.
Private Sub say_helloworld_Click() Dim password As String password = "Admin#1" Dim num As Integer num = 1234 Dim BirthDay As Date BirthDay = DateValue("30 / 10 / 2020") MsgBox "Passowrd is " & password & Chr(10) & "Value of num is " & num & Chr(10) & "Value of Birthday is " & BirthDay End Sub
Output
Upon executing the script, the output will be as shown in the following screenshot.
VBA — Constants
Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant value, the script execution ends up with an error. Constants are declared the same way the variables are declared.
Following are the rules for naming a constant.
-
You must use a letter as the first character.
-
You can’t use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the name.
-
Name can’t exceed 255 characters in length.
-
You cannot use Visual Basic reserved keywords as variable name.
Syntax
In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to change the value of the constant.
Const <<constant_name>> As <<constant_type>> = <<constant_value>>
Example
Let us create a button «Constant_demo» to demonstrate how to work with constants.
Private Sub Constant_demo_Click() Const MyInteger As Integer = 42 Const myDate As Date = #2/2/2020# Const myDay As String = "Sunday" MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is " & myDate & Chr(10) & "myDay is " & myDay End Sub
Output
Upon executing the script, the output will be displayed as shown in the following screenshot.
VBA — Operators
An Operator can be defined using a simple expression — 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called operator. VBA supports following types of operators −
- Arithmetic Operators
- Comparison Operators
- Logical (or Relational) Operators
- Concatenation Operators
The Arithmatic Operators
Following arithmetic operators are supported by VBA.
Assume variable A holds 5 and variable B holds 10, then −
Show Examples
Operator | Description | Example |
---|---|---|
+ | Adds the two operands | A + B will give 15 |
— | Subtracts the second operand from the first | A — B will give -5 |
* | Multiplies both the operands | A * B will give 50 |
/ | Divides the numerator by the denominator | B / A will give 2 |
% | Modulus operator and the remainder after an integer division | B % A will give 0 |
^ | Exponentiation operator | B ^ A will give 100000 |
The Comparison Operators
There are following comparison operators supported by VBA.
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator | Description | Example |
---|---|---|
= | Checks if the value of the two operands are equal or not. If yes, then the condition is true. | (A = B) is False. |
<> | Checks if the value of the two operands are equal or not. If the values are not equal, then the condition is true. | (A <> B) is True. |
> | Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition is true. | (A > B) is False. |
< | Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition is true. | (A < B) is True. |
>= | Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition is true. | (A >= B) is False. |
<= | Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition is true. | (A <= B) is True. |
The Logical Operators
Following logical operators are supported by VBA.
Assume variable A holds 10 and variable B holds 0, then −
Show Examples
Operator | Description | Example |
---|---|---|
AND | Called Logical AND operator. If both the conditions are True, then the Expression is true. | a<>0 AND b<>0 is False. |
OR | Called Logical OR Operator. If any of the two conditions are True, then the condition is true. | a<>0 OR b<>0 is true. |
NOT | Called Logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make false. | NOT(a<>0 OR b<>0) is false. |
XOR | Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to be True, the result is True. | (a<>0 XOR b<>0) is true. |
The Concatenation Operators
Following Concatenation operators are supported by VBA.
Assume variable A holds 5 and variable B holds 10 then −
Show Examples
Operator | Description | Example |
---|---|---|
+ | Adds two Values as Variable. Values are Numeric | A + B will give 15 |
& | Concatenates two Values | A & B will give 510 |
Assume variable A = «Microsoft» and variable B = «VBScript», then −
Operator | Description | Example |
---|---|---|
+ | Concatenates two Values | A + B will give MicrosoftVBScript |
& | Concatenates two Values | A & B will give MicrosoftVBScript |
Note − Concatenation Operators can be used for both numbers and strings. The output depends on the context, if the variables hold numeric value or string value.
VBA — Decisions
Decision making allows the programmers to control the execution flow of a script or one of its sections. The execution is governed by one or more conditional statements.
Following is the general form of a typical decision making structure found in most of the programming languages.
VBA provides the following types of decision making statements. Click the following links to check their details.
Sr.No. | Statement & Description |
---|---|
1 |
if statement
An if statement consists of a Boolean expression followed by one or more statements. |
2 |
if..else statement
An if else statement consists of a Boolean expression followed by one or more statements. If the condition is True, the statements under If statements are executed. If the condition is false, the Else part of the script is executed. |
3 |
if…elseif..else statement
An if statement followed by one or more ElseIf statements, that consists of Boolean expressions and then followed by an optional else statement, which executes when all the condition become false. |
4 |
nested if statements
An if or elseif statement inside another if or elseif statement(s). |
5 |
switch statement
A switch statement allows a variable to be tested for equality against a list of values. |
VBA — Loops
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Following is the general form of a loop statement in VBA.
VBA provides the following types of loops to handle looping requirements. Click the following links to check their detail.
Sr.No. | Loop Type & Description |
---|---|
1 |
for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
2 |
for ..each loop
This is executed if there is at least one element in the group and reiterated for each element in a group. |
3 |
while..wend loop
This tests the condition before executing the loop body. |
4 |
do..while loops
The do..While statements will be executed as long as the condition is True.(i.e.,) The Loop should be repeated till the condition is False. |
5 |
do..until loops
The do..Until statements will be executed as long as the condition is False.(i.e.,) The Loop should be repeated till the condition is True. |
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all the remaining statements in the loop are NOT executed.
VBA supports the following control statements. Click the following links to check their detail.
S.No. | Control Statement & Description |
---|---|
1 |
Exit For statement
Terminates the For loop statement and transfers the execution to the statement immediately following the loop |
2 |
Exit Do statement
Terminates the Do While statement and transfers the execution to the statement immediately following the loop |
VBA — Strings
Strings are a sequence of characters, which can consist of either alphabets, numbers, special characters, or all of them. A variable is said to be a string if it is enclosed within double quotes » «.
Syntax
variablename = "string"
Examples
str1 = "string" ' Only Alphabets str2 = "132.45" ' Only Numbers str3 = "!@#$;*" ' Only Special Characters Str4 = "Asc23@#" ' Has all the above
String Functions
There are predefined VBA String functions, which help the developers to work with the strings very effectively. Following are String methods that are supported in VBA. Please click on each one of the methods to know in detail.
Sr.No. | Function Name & Description |
---|---|
1 |
InStr
Returns the first occurrence of the specified substring. Search happens from the left to the right. |
2 |
InstrRev
Returns the first occurrence of the specified substring. Search happens from the right to the left. |
3 |
Lcase
Returns the lower case of the specified string. |
4 |
Ucase
Returns the upper case of the specified string. |
5 | Left
Returns a specific number of characters from the left side of the string. |
6 | Right
Returns a specific number of characters from the right side of the string. |
7 |
Mid
Returns a specific number of characters from a string based on the specified parameters. |
8 |
Ltrim
Returns a string after removing the spaces on the left side of the specified string. |
9 |
Rtrim
Returns a string after removing the spaces on the right side of the specified string. |
10 |
Trim
Returns a string value after removing both the leading and the trailing blank spaces. |
11 |
Len
Returns the length of the given string. |
12 |
Replace
Returns a string after replacing a string with another string. |
13 |
Space
Fills a string with the specified number of spaces. |
14 |
StrComp
Returns an integer value after comparing the two specified strings. |
15 |
String
Returns a string with a specified character for specified number of times. |
16 |
StrReverse
Returns a string after reversing the sequence of the characters of the given string. |
VBA — Date-Time Function
VBScript Date and Time Functions help the developers to convert date and time from one format to another or to express the date or time value in the format that suits a specific condition.
Date Functions
Sr.No. | Function & Description |
---|---|
1 |
Date
A Function, which returns the current system date. |
2 |
CDate
A Function, which converts a given input to date. |
3 |
DateAdd
A Function, which returns a date to which a specified time interval has been added. |
4 |
DateDiff
A Function, which returns the difference between two time period. |
5 |
DatePart
A Function, which returns a specified part of the given input date value. |
6 |
DateSerial
A Function, which returns a valid date for the given year, month, and date. |
7 |
FormatDateTime
A Function, which formats the date based on the supplied parameters. |
8 |
IsDate
A Function, which returns a Boolean Value whether or not the supplied parameter is a date. |
9 |
Day
A Function, which returns an integer between 1 and 31 that represents the day of the specified date. |
10 |
Month
A Function, which returns an integer between 1 and 12 that represents the month of the specified date. |
11 |
Year
A Function, which returns an integer that represents the year of the specified date. |
12 |
MonthName
A Function, which returns the name of the particular month for the specified date. |
13 |
WeekDay
A Function, which returns an integer(1 to 7) that represents the day of the week for the specified day. |
14 |
WeekDayName
A Function, which returns the weekday name for the specified day. |
Time Functions
Sr.No. | Function & Description |
---|---|
1 |
Now
A Function, which returns the current system date and time. |
2 |
Hour
A Function, which returns an integer between 0 and 23 that represents the hour part of the given time. |
3 |
Minute
A Function, which returns an integer between 0 and 59 that represents the minutes part of the given time. |
4 | Second
A Function, which returns an integer between 0 and 59 that represents the seconds part of the given time. |
5 | Time
A Function, which returns the current system time. |
6 |
Timer
A Function, which returns the number of seconds and milliseconds since 12:00 AM. |
7 |
TimeSerial
A Function, which returns the time for the specific input of hour, minute and second. |
8 |
TimeValue
A Function, which converts the input string to a time format. |
VBA — Arrays
We know very well that a variable is a container to store a value. Sometimes, developers are in a position to hold more than one value in a single variable at a time. When a series of values are stored in a single variable, then it is known as an array variable.
Array Declaration
Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis. In the following example, the size of the array is mentioned in the brackets.
'Method 1 : Using Dim Dim arr1() 'Without Size 'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5 'Method 3 : using 'Array' Parameter Dim arr3 arr3 = Array("apple","Orange","Grapes")
-
Although, the array size is indicated as 5, it can hold 6 values as array index starts from ZERO.
-
Array Index cannot be negative.
-
VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string, or characters in a single array variable.
Assigning Values to an Array
The values are assigned to the array by specifying an array index value against each one of the values to be assigned. It can be a string.
Example
Add a button and add the following function.
Private Sub Constant_demo_Click() Dim arr(5) arr(0) = "1" 'Number as String arr(1) = "VBScript" 'String arr(2) = 100 'Number arr(3) = 2.45 'Decimal Number arr(4) = #10/07/2013# 'Date arr(5) = #12.45 PM# 'Time msgbox("Value stored in Array index 0 : " & arr(0)) msgbox("Value stored in Array index 1 : " & arr(1)) msgbox("Value stored in Array index 2 : " & arr(2)) msgbox("Value stored in Array index 3 : " & arr(3)) msgbox("Value stored in Array index 4 : " & arr(4)) msgbox("Value stored in Array index 5 : " & arr(5)) End Sub
When you execute the above function, it produces the following output.
Value stored in Array index 0 : 1 Value stored in Array index 1 : VBScript Value stored in Array index 2 : 100 Value stored in Array index 3 : 2.45 Value stored in Array index 4 : 7/10/2013 Value stored in Array index 5 : 12:45:00 PM
Multi-Dimensional Arrays
Arrays are not just limited to a single dimension, however, they can have a maximum of 60 dimensions. Two-dimensional arrays are the most commonly used ones.
Example
In the following example, a multi-dimensional array is declared with 3 rows and 4 columns.
Private Sub Constant_demo_Click() Dim arr(2,3) as Variant ' Which has 3 rows and 4 columns arr(0,0) = "Apple" arr(0,1) = "Orange" arr(0,2) = "Grapes" arr(0,3) = "pineapple" arr(1,0) = "cucumber" arr(1,1) = "beans" arr(1,2) = "carrot" arr(1,3) = "tomato" arr(2,0) = "potato" arr(2,1) = "sandwitch" arr(2,2) = "coffee" arr(2,3) = "nuts" msgbox("Value in Array index 0,1 : " & arr(0,1)) msgbox("Value in Array index 2,2 : " & arr(2,2)) End Sub
When you execute the above function, it produces the following output.
Value stored in Array index : 0 , 1 : Orange Value stored in Array index : 2 , 2 : coffee
ReDim Statement
ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage space.
Syntax
ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
Parameter Description
-
Preserve − An optional parameter used to preserve the data in an existing array when you change the size of the last dimension.
-
Varname − A required parameter, which denotes the name of the variable, which should follow the standard variable naming conventions.
-
Subscripts − A required parameter, which indicates the size of the array.
Example
In the following example, an array has been redefined and then the values preserved when the existing size of the array is changed.
Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements will be lost.
Private Sub Constant_demo_Click() Dim a() as variant i = 0 redim a(5) a(0) = "XYZ" a(1) = 41.25 a(2) = 22 REDIM PRESERVE a(7) For i = 3 to 7 a(i) = i Next 'to Fetch the output For i = 0 to ubound(a) Msgbox a(i) Next End Sub
When you execute the above function, it produces the following output.
XYZ 41.25 22 3 4 5 6 7
Array Methods
There are various inbuilt functions within VBScript which help the developers to handle arrays effectively. All the methods that are used in conjunction with arrays are listed below. Please click on the method name to know about it in detail.
Sr.No. | Function & Description |
---|---|
1 |
LBound
A Function, which returns an integer that corresponds to the smallest subscript of the given arrays. |
2 |
UBound
A Function, which returns an integer that corresponds to the largest subscript of the given arrays. |
3 |
Split
A Function, which returns an array that contains a specified number of values. Split based on a delimiter. |
4 |
Join
A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method. |
5 |
Filter
A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria. |
6 |
IsArray
A Function, which returns a boolean value that indicates whether or not the input variable is an array. |
7 |
Erase
A Function, which recovers the allocated memory for the array variables. |
VBA — User Defined Functions
A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code over and over again. This enables the programmers to divide a big program into a number of small and manageable functions.
Apart from inbuilt functions, VBA allows to write user-defined functions as well. In this chapter, you will learn how to write your own functions in VBA.
Function Definition
A VBA function can have an optional return statement. This is required if you want to return a value from a function.
For example, you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.
Note − A function can return multiple values separated by a comma as an array assigned to the function name itself.
Before we use a function, we need to define that particular function. The most common way to define a function in VBA is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with End Function keyword, which indicates the end of the function. Following is the basic syntax.
Syntax
Add a button and add the following function.
Function Functionname(parameter-list) statement 1 statement 2 statement 3 ....... statement n End Function
Example
Add the following function which returns the area. Note that a value/values can be returned with the function name itself.
Function findArea(Length As Double, Optional Width As Variant) If IsMissing(Width) Then findArea = Length * Length Else findArea = Length * Width End If End Function
Calling a Function
To invoke a function, call the function using the function name as shown in the following screenshot.
The output of the area as shown below will be displayed to the user.
VBA — Sub Procedure
Sub Procedures are similar to functions, however there are a few differences.
-
Sub procedures DO NOT Return a value while functions may or may not return a value.
-
Sub procedures CAN be called without a call keyword.
-
Sub procedures are always enclosed within Sub and End Sub statements.
Example
Sub Area(x As Double, y As Double) MsgBox x * y End Sub
Calling Procedures
To invoke a Procedure somewhere in the script, you can make a call from a function. We will not be able to use the same way as that of a function as sub procedure WILL NOT return a value.
Function findArea(Length As Double, Width As Variant) area Length, Width ' To Calculate Area 'area' sub proc is called End Function
Now you will be able to call the function only but not the sub procedure as shown in the following screenshot.
The area is calculated and shown only in the Message box.
The result cell displays ZERO as the area value is NOT returned from the function. In short, you cannot make a direct call to a sub procedure from the excel worksheet.
VBA — Events
VBA, an event-driven programming can be triggered when you change a cell or range of cell values manually. Change event may make things easier, but you can very quickly end a page full of formatting. There are two kinds of events.
- Worksheet Events
- Workbook Events
Worksheet Events
Worksheet Events are triggered when there is a change in the worksheet. It is created by performing a right-click on the sheet tab and choosing ‘view code’, and later pasting the code.
The user can select each one of those worksheets and choose «WorkSheet» from the drop down to get the list of all supported Worksheet events.
Following are the supported worksheet events that can be added by the user.
Private Sub Worksheet_Activate() Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) Private Sub Worksheet_Calculate() Private Sub Worksheet_Change(ByVal Target As Range) Private Sub Worksheet_Deactivate() Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink) Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Example
Let us say, we just need to display a message before double click.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) MsgBox "Before Double Click" End Sub
Output
Upon double-clicking on any cell, the message box is displayed to the user as shown in the following screenshot.
Workbook Events
Workbook events are triggered when there is a change in the workbook on the whole. We can add the code for workbook events by selecting the ‘ThisWorkbook’ and selecting ‘workbook’ from the dropdown as shown in the following screenshot. Immediately Workbook_open sub procedure is displayed to the user as seen in the following screenshot.
Following are the supported Workbook events that can be added by the user.
Private Sub Workbook_AddinUninstall() Private Sub Workbook_BeforeClose(Cancel As Boolean) Private Sub Workbook_BeforePrint(Cancel As Boolean) Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Private Sub Workbook_Deactivate() Private Sub Workbook_NewSheet(ByVal Sh As Object) Private Sub Workbook_Open() Private Sub Workbook_SheetActivate(ByVal Sh As Object) Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Private Sub Workbook_SheetCalculate(ByVal Sh As Object) Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) Private Sub Workbook_SheetDeactivate(ByVal Sh As Object) Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink) Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) Private Sub Workbook_WindowActivate(ByVal Wn As Window) Private Sub Workbook_WindowDeactivate(ByVal Wn As Window) Private Sub Workbook_WindowResize(ByVal Wn As Window)
Example
Let us say, we just need to display a message to the user that a new sheet is created successfully, whenever a new sheet is created.
Private Sub Workbook_NewSheet(ByVal Sh As Object) MsgBox "New Sheet Created Successfully" End Sub
Output
Upon creating a new excel sheet, a message is displayed to the user as shown in the following screenshot.
VBA — Error Handling
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
Syntax errors
Syntax errors, also called as parsing errors, occur at the interpretation time for VBScript. For example, the following line causes a syntax error because it is missing a closing parenthesis.
Function ErrorHanlding_Demo() dim x,y x = "Tutorialspoint" y = Ucase(x End Function
Runtime errors
Runtime errors, also called exceptions, occur during execution, after interpretation.
For example, the following line causes a runtime error because here the syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function.
Function ErrorHanlding_Demo1() Dim x,y x = 10 y = 20 z = fnadd(x,y) a = fnmultiply(x,y) End Function Function fnadd(x,y) fnadd = x + y End Function
Logical Errors
Logical errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program.
For example, dividing a number by zero or a script that is written which enters into infinite loop.
Err Object
Assume if we have a runtime error, then the execution stops by displaying the error message. As a developer, if we want to capture the error, then Error Object is used.
Example
In the following example, Err.Number gives the error number and Err.Description gives the error description.
Err.Raise 6 ' Raise an overflow error. MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear ' Clear the error.
Error Handling
VBA enables an error-handling routine and can also be used to disable an error-handling routine. Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and the execution stops abruptly.
On Error { GoTo [ line | 0 | -1 ] | Resume Next }
Sr.No. | Keyword & Description |
---|---|
1 |
GoTo line Enables the error-handling routine that starts at the line specified in the required line argument. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur. |
2 |
GoTo 0 Disables the enabled error handler in the current procedure and resets it to Nothing. |
3 |
GoTo -1 Disables the enabled exception in the current procedure and resets it to Nothing. |
4 |
Resume Next Specifies that when a run-time error occurs, the control goes to the statement immediately following the statement where the error occurred, and the execution continues from that point. |
Example
Public Sub OnErrorDemo() On Error GoTo ErrorHandler ' Enable error-handling routine. Dim x, y, z As Integer x = 50 y = 0 z = x / y ' Divide by ZERO Error Raises ErrorHandler: ' Error-handling routine. Select Case Err.Number ' Evaluate error number. Case 10 ' Divide by zero error MsgBox ("You attempted to divide by zero!") Case Else MsgBox "UNKNOWN ERROR - Error# " & Err.Number & " : " & Err.Description End Select Resume Next End Sub
VBA — Excel Objects
When programming using VBA, there are few important objects that a user would be dealing with.
- Application Objects
- Workbook Objects
- Worksheet Objects
- Range Objects
Application Objects
The Application object consists of the following −
- Application-wide settings and options.
- Methods that return top-level objects, such as ActiveCell, ActiveSheet, and so on.
Example
'Example 1 : Set xlapp = CreateObject("Excel.Sheet") xlapp.Application.Workbooks.Open "C:test.xls" 'Example 2 : Application.Windows("test.xls").Activate 'Example 3: Application.ActiveCell.Font.Bold = True
Workbook Objects
The Workbook object is a member of the Workbooks collection and contains all the Workbook objects currently open in Microsoft Excel.
Example
'Ex 1 : To close Workbooks Workbooks.Close 'Ex 2 : To Add an Empty Work Book Workbooks.Add 'Ex 3: To Open a Workbook Workbooks.Open FileName:="Test.xls", ReadOnly:=True 'Ex : 4 - To Activate WorkBooks Workbooks("Test.xls").Worksheets("Sheet1").Activate
Worksheet Objects
The Worksheet object is a member of the Worksheets collection and contains all the Worksheet objects in a workbook.
Example
'Ex 1 : To make it Invisible Worksheets(1).Visible = False 'Ex 2 : To protect an WorkSheet Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True
Range Objects
Range Objects represent a cell, a row, a column, or a selection of cells containing one or more continuous blocks of cells.
'Ex 1 : To Put a value in the cell A5 Worksheets("Sheet1").Range("A5").Value = "5235" 'Ex 2 : To put a value in range of Cells Worksheets("Sheet1").Range("A1:A4").Value = 5
VBA — Text Files
You can also read Excel File and write the contents of the cell into a Text File using VBA. VBA allows the users to work with text files using two methods −
- File System Object
- using Write Command
File System Object (FSO)
As the name suggests, FSOs help the developers to work with drives, folders, and files. In this section, we will discuss how to use a FSO.
Sr.No. | Object Type & Description |
---|---|
1 |
Drive Drive is an Object. Contains methods and properties that allow you to gather information about a drive attached to the system. |
2 |
Drives Drives is a Collection. It provides a list of the drives attached to the system, either physically or logically. |
3 |
File File is an Object. It contains methods and properties that allow developers to create, delete, or move a file. |
4 |
Files Files is a Collection. It provides a list of all the files contained within a folder. |
5 |
Folder Folder is an Object. It provides methods and properties that allow the developers to create, delete, or move folders. |
6 |
Folders Folders is a Collection. It provides a list of all the folders within a folder. |
7 |
TextStream TextStream is an Object. It enables the developers to read and write text files. |
Drive
Drive is an object, which provides access to the properties of a particular disk drive or network share. Following properties are supported by Drive object −
- AvailableSpace
- DriveLetter
- DriveType
- FileSystem
- FreeSpace
- IsReady
- Path
- RootFolder
- SerialNumber
- ShareName
- TotalSize
- VolumeName
Example
Step 1 − Before proceeding to scripting using FSO, we should enable Microsoft Scripting Runtime. To do the same, navigate to Tools → References as shown in the following screenshot.
Step 2 − Add «Microsoft Scripting RunTime» and Click OK.
Step 3 − Add Data that you would like to write in a Text File and add a Command Button.
Step 4 − Now it is time to Script.
Private Sub fn_write_to_text_Click() Dim FilePath As String Dim CellData As String Dim LastCol As Long Dim LastRow As Long Dim fso As FileSystemObject Set fso = New FileSystemObject Dim stream As TextStream LastCol = ActiveSheet.UsedRange.Columns.Count LastRow = ActiveSheet.UsedRange.Rows.Count ' Create a TextStream. Set stream = fso.OpenTextFile("D:TrySupport.log", ForWriting, True) CellData = "" For i = 1 To LastRow For j = 1 To LastCol CellData = Trim(ActiveCell(i, j).Value) stream.WriteLine "The Value at location (" & i & "," & j & ")" & CellData Next j Next i stream.Close MsgBox ("Job Done") End Sub
Output
When executing the script, ensure that you place the cursor in the first cell of the worksheet. The Support.log file is created as shown in the following screenshot under «D:Try».
The Contents of the file are shown in the following screenshot.
Write Command
Unlike FSO, we need NOT add any references, however, we will NOT be able to work with drives, files and folders. We will be able to just add the stream to the text file.
Example
Private Sub fn_write_to_text_Click() Dim FilePath As String Dim CellData As String Dim LastCol As Long Dim LastRow As Long LastCol = ActiveSheet.UsedRange.Columns.Count LastRow = ActiveSheet.UsedRange.Rows.Count FilePath = "D:Trywrite.txt" Open FilePath For Output As #2 CellData = "" For i = 1 To LastRow For j = 1 To LastCol CellData = "The Value at location (" & i & "," & j & ")" & Trim(ActiveCell(i, j).Value) Write #2, CellData Next j Next i Close #2 MsgBox ("Job Done") End Sub
Output
Upon executing the script, the «write.txt» file is created in the location «D:Try» as shown in the following screenshot.
The contents of the file are shown in the following screenshot.
VBA — Programming Charts
Using VBA, you can generate charts based on certain criteria. Let us take a look at it using an example.
Step 1 − Enter the data against which the graph has to be generated.
Step 2 − Create 3 buttons — one to generate a bar graph, another to generate a pie chart, and another to generate a column chart.
Step 3 − Develop a Macro to generate each one of these type of charts.
' Procedure to Generate Pie Chart Private Sub fn_generate_pie_graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlPie Next cht End Sub ' Procedure to Generate Bar Graph Private Sub fn_Generate_Bar_Graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlBar Next cht End Sub ' Procedure to Generate Column Graph Private Sub fn_generate_column_graph_Click() Dim cht As ChartObject For Each cht In Worksheets(1).ChartObjects cht.Chart.Type = xlColumn Next cht End Sub
Step 4 − Upon clicking the corresponding button, the chart is created. In the following output, click on generate Pie Chart button.
VBA — User Forms
A User Form is a custom-built dialog box that makes a user data entry more controllable and easier to use for the user. In this chapter, you will learn to design a simple form and add data into excel.
Step 1 − Navigate to VBA Window by pressing Alt+F11 and Navigate to «Insert» Menu and select «User Form». Upon selecting, the user form is displayed as shown in the following screenshot.
Step 2 − Design the forms using the given controls.
Step 3 − After adding each control, the controls have to be named. Caption corresponds to what appears on the form and name corresponds to the logical name that will be appearing when you write VBA code for that element.
Step 4 − Following are the names against each one of the added controls.
Control | Logical Name | Caption |
---|---|---|
From | frmempform | Employee Form |
Employee ID Label Box | empid | Employee ID |
firstname Label Box | firstname | First Name |
lastname Label Box | lastname | Last Name |
dob Label Box | dob | Date of Birth |
mailid Label Box | mailid | Email ID |
Passportholder Label Box | Passportholder | Passport Holder |
Emp ID Text Box | txtempid | NOT Applicable |
First Name Text Box | txtfirstname | NOT Applicable |
Last Name Text Box | txtlastname | NOT Applicable |
Email ID Text Box | txtemailid | NOT Applicable |
Date Combo Box | cmbdate | NOT Applicable |
Month Combo Box | cmbmonth | NOT Applicable |
Year Combo Box | cmbyear | NOT Applicable |
Yes Radio Button | radioyes | Yes |
No Radio Button | radiono | No |
Submit Button | btnsubmit | Submit |
Cancel Button | btncancel | Cancel |
Step 5 − Add the code for the form load event by performing a right-click on the form and selecting ‘View Code’.
Step 6 − Select ‘Userform’ from the objects drop-down and select ‘Initialize’ method as shown in the following screenshot.
Step 7 − Upon Loading the form, ensure that the text boxes are cleared, drop-down boxes are filled and Radio buttons are reset.
Private Sub UserForm_Initialize() 'Empty Emp ID Text box and Set the Cursor txtempid.Value = "" txtempid.SetFocus 'Empty all other text box fields txtfirstname.Value = "" txtlastname.Value = "" txtemailid.Value = "" 'Clear All Date of Birth Related Fields cmbdate.Clear cmbmonth.Clear cmbyear.Clear 'Fill Date Drop Down box - Takes 1 to 31 With cmbdate .AddItem "1" .AddItem "2" .AddItem "3" .AddItem "4" .AddItem "5" .AddItem "6" .AddItem "7" .AddItem "8" .AddItem "9" .AddItem "10" .AddItem "11" .AddItem "12" .AddItem "13" .AddItem "14" .AddItem "15" .AddItem "16" .AddItem "17" .AddItem "18" .AddItem "19" .AddItem "20" .AddItem "21" .AddItem "22" .AddItem "23" .AddItem "24" .AddItem "25" .AddItem "26" .AddItem "27" .AddItem "28" .AddItem "29" .AddItem "30" .AddItem "31" End With 'Fill Month Drop Down box - Takes Jan to Dec With cmbmonth .AddItem "JAN" .AddItem "FEB" .AddItem "MAR" .AddItem "APR" .AddItem "MAY" .AddItem "JUN" .AddItem "JUL" .AddItem "AUG" .AddItem "SEP" .AddItem "OCT" .AddItem "NOV" .AddItem "DEC" End With 'Fill Year Drop Down box - Takes 1980 to 2014 With cmbyear .AddItem "1980" .AddItem "1981" .AddItem "1982" .AddItem "1983" .AddItem "1984" .AddItem "1985" .AddItem "1986" .AddItem "1987" .AddItem "1988" .AddItem "1989" .AddItem "1990" .AddItem "1991" .AddItem "1992" .AddItem "1993" .AddItem "1994" .AddItem "1995" .AddItem "1996" .AddItem "1997" .AddItem "1998" .AddItem "1999" .AddItem "2000" .AddItem "2001" .AddItem "2002" .AddItem "2003" .AddItem "2004" .AddItem "2005" .AddItem "2006" .AddItem "2007" .AddItem "2008" .AddItem "2009" .AddItem "2010" .AddItem "2011" .AddItem "2012" .AddItem "2013" .AddItem "2014" End With 'Reset Radio Button. Set it to False when form loads. radioyes.Value = False radiono.Value = False End Sub
Step 8 − Now add the code to the Submit button. Upon clicking the submit button, the user should be able to add the values into the worksheet.
Private Sub btnsubmit_Click() Dim emptyRow As Long 'Make Sheet1 active Sheet1.Activate 'Determine emptyRow emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1 'Transfer information Cells(emptyRow, 1).Value = txtempid.Value Cells(emptyRow, 2).Value = txtfirstname.Value Cells(emptyRow, 3).Value = txtlastname.Value Cells(emptyRow, 4).Value = cmbdate.Value & "/" & cmbmonth.Value & "/" & cmbyear.Value Cells(emptyRow, 5).Value = txtemailid.Value If radioyes.Value = True Then Cells(emptyRow, 6).Value = "Yes" Else Cells(emptyRow, 6).Value = "No" End If End Sub
Step 9 − Add a method to close the form when the user clicks the Cancel button.
Private Sub btncancel_Click() Unload Me End Sub
Step 10 − Execute the form by clicking the «Run» button. Enter the values into the form and click the ‘Submit’ button. Automatically the values will flow into the worksheet as shown in the following screenshot.
Learning Objectives:
- What is VBA? Why VBA?
- Hello World
- What is function? What is subroutine?
- How to define variable?
- VBA Objects
- Record Macro
What is VBA? Why VBA?
VBA stands for Visual Basic Application. It shares the same syntax as Basic language. Every operation you can perform in Excel using keyboard and mouse can be represented by VBA code. Hence, it allows a lot of flexibility and functionality when using Excel.
VBA improves your logical thinking skills, and prepares you for other programming languages, since it is quite basic and the thinking processes can be applied to other languages (such as R in the next chapter). It is ideal for repetitive tasks (e.g. code a function that will run the same process each time, instead of typing it out manually)
VBA Basics
Visual Basic Editor
First, we need to open Visual Basic Editor (VBE). There are two ways to open VBE: (1) Press ALT+F11 to open the Visual Basic Editor and (2) File > Options > Customize Ribbon > Developer(check the box) Developer Tab > Visual Basic
In the toolbar, select Insert textgreater Module. Make sure you insert the module into the workbook that you are working on.
Module is the place where you store the code. You can have as many modules as you want. You can put your code into different modules according to the functions they perform.
Hello World
We will use MsgBox function in VBA to create a popup window in Excel to say hello world.
Sub HelloWorld()
MsgBox ("Hello World! I like VBA!")
End Sub
Variable
Dim
is used to define variables. The syntax looks like this:
Dim a As Integer
Dim b As Double
Variable | Range |
---|---|
Integer | From –32,768 to 32,767 |
Long | From –2,147,483,648 to 2,147,486,647 |
Single | From –3402823E38 to –1.401298E–45 or 1.401298E–45 to 3.402823E38 |
Double | From –1.79769313486232E308 to –4.94065645841247E–324 or 1.79769313486232E308 to 4.94065645841247E–324 |
Boolean | Either 1 or 0 |
String | 1 to 65,400 characters |
Array | An array is a group of variables |
Variant | Anything |
The following example display the value of variable.
Sub DisplayVar()
Dim a as Integer
a = 10
Msgbox("My variable has the value of " & a &".")
End Sub
One useful function of MsgBox is to check if certain sections of your code are running properly.
Subroutine and Function
In terms of the code that you can program inside, a Function
and a Sub
are similar. The main difference is that a Sub performs a task, but returns no output, while a Function takes in input and returns output.
Our Hello World is an example of Sub. The structure of sub is that it starts with Sub
together with the name of the Sub, and it ends with End Sub
. The code to run is in between.
Sub Name()
---Task 1---
---Task 2---
End Sub
Inside a subroutine, we can call other subroutine. The following subroutine calls HelloWorld subroutine twice.
Sub CallAnotherSub()
Call HelloWorld
Call HelloWorld
End Sub
The syntax for a function is similar. The structure of function is that it starts with Function
together with the name of the Sub, and it ends with End Function
. The code to run is in between.
However, two key differences: (1) we have to enter the variable to be processed and its variable type, and (2) we have to tell what is the output of the function.
Function Name( Variable As Variable Type)
---Content here---
Name = .....
End Function
Let us create a simple function that calculate length hypotenuse of a right-angle triangle. To calculate the length hypotenuse, we need to have lengths of the sides. Hence, since sides are number, we use double. Since the formula is square root of sum of squared length of the sides, we will use ^
as power and Sqr
as square root function.
Function Hypotenuse(a As Double, b As Double)
Hypotenuse = Sqr(a ^ 2 + b ^ 2)
End Function
Go to spreadsheet then type =Hypotenus(3,4)
into formula of any cell. You should get 5.
We can also call function inside a subroutine. The following subroutine calls the hypotenus function.
Sub MsgFunction()
Msgbox("Secret is " & ABC(3,4))
End Sub
Recall the spreadsheet example of calculation of EMA. S
A | B | C | |
---|---|---|---|
1 | n | 5 | |
2 | beta | =2/(A1+1) |
|
3 | Date | Price | EMA(n) |
4 | 02-May-16 | 10 | |
… | |||
8 | 06-May-16 | 8 | =AVERAGE(B4:B8) |
9 | 07-May-16 | =$B$2*B9+(1-$B$2)*C8 |
Function EMA(EMAYes As Double, price As Double, n As Integer)
beta = 2 / (n + 1)
EMA = beta * price + (1 - beta) * EMAYes
End Function
We can simplify our spreadsheet using the VBA code as shown below.
A | B | C | |
---|---|---|---|
1 | n | 5 | |
2 | beta | =2/(A1+1) |
|
3 | Date | Price | EMA(n) |
4 | 02-May-16 | 10 | |
… | |||
8 | 06-May-16 | 8 | =AVERAGE(B4:B8) |
9 | 07-May-16 | =EMA(C7,B8,$B$1) |
Objects
Objects are special type of variables. In particular, they represent elements of Excel. Common used objects include
- cell,
- range,
- workbook,
- worksheet,
- active objects,
- application and
- chart.
To use object, we can use either method or property.
Method is an action: activate, select, delete, value, formula, text, clear, copy, paste.
Property is description: name, visible
Using a metaphor: If object is noun, method is verb and property is adjective
Collections is an object that contain a group of the same object. For example, Worksheets
contains all worksheet objects, and Workbooks
contains all workbook objects. To call a particular worksheet, we would call the name of the particular sheet in Worksheets.
Cells
Cells refers to one cell in a range but it is using coordinate instead of R1C1 as cell reference. The syntax is Cells(row, column)
.
For example, the following sets the second row in the range C2:C5 to value of 3. In the other words, C3 is set to 3.
Sub RangeAndCell()
Range("C2:C5").Cells(2, 1).Value = 3
End Sub
If the worksheet name is not explicitly stated, it is assumed that the code works on the active sheet.
Sub WorkingOnCell()
Cells(1,1).value = 5
End Sub
Offset refers to another cell, taking reference from the current active cell.
Sub CellOffSet()
Cells(1,1) = 5
Cells(1,1).Offset(0,1).Formula = "=A1+1"
Cells(1,1).Offset(1,0).Formula = "=A1+2"
End Sub
Then cell A1 is 5, cell B1 is 6 and cell A2 is 7
Range
Range is a collection of cells.
Sub SheetAndRange()
Worksheets("sheet1").Range("A1").Value = 3
End Sub
This causes the worksheet named sheet1 to have the value 3 in cell A1. If the worksheet name is not explicitly stated, it is assumed that the code works on the active sheet.
The following code shows the formula, value, text property of range.
Sub WorkingOnRange()
Range("A1").Formula = "=RAND()"
Range("B1:E3").Value = 6
Range("A1").Text="3+4"
End Sub
The following code shows how to do copy, paste and paste special (value).
Sub CopyAndPaste()
Range("A1:B5").Formula = "=RAND()"
Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C2:C5").PasteSpecial
End Sub
The following code shows how to obtain input from the spreadsheet.
Sub GetFromSheet ()
Dim a as Integer
Range("A1").Formula ="=RANDBETWEEN(1,6)"
a = Range("A1").Value
Msgbox(a)
End Sub
Worksheets
Worksheets are what we use in Excel, we can create multiple sheets and give them unique names etc. We can also add new sheets or delete sheets in our VBA code.
Sub AddSheet()
WorkSheets.Add
WorkSheets(ActiveSheet.Name).Name = "MySheet"
End Sub
Sub DelSheet()
Application.DisplayAlerts = False
WorkSheets("MySheet").Delete
Application.DisplayAlerts = True
End Sub
We can also activate, rename or hide/unhide worksheets:
Worksheets("sheet1").Activate
Worksheets("sheet1").Delete
Worksheets("sheet2").Select
Worksheets("sheet1").Name="Me"
Worksheets("sheet3").Visible=False
Worksheets.Add
Workbook
Workbook object is essentially one excel file.
Sub WorkBookActiveName()
Workbooks("book1").Activate
MsgBox (Workbooks("book1").ActiveSheet.Name)
End Sub
Application
The following four lines show how to select using application objects. The first line chooses cell A1 in the active 2. The second line chooses the second column (of the active worksheet). The third line chooses the first row (of the active worksheet). The forth line chooses the worksheet with name sheet1
.
Application.ActiveSheet.Cells(1,1).Select
Application.Columns(2).Select
Application.Rows(1).Select
Application.Sheets("sheet1").Select
The following shows some actions in spreadsheet. The first line asks the program to redo all calculation for the spreadsheet. The second line perform redo
.
Application.Calculate
Application.Undo
Worksheet functions are application objects. They can be used directly. For example, the following three lines of code corresponds to calling COUNT
, SUM
and AVERAGE
functions from the spreadsheet.
Application.WorksheetFunction.Count
Application.WorksheetFunction.Sum
Application.WorksheetFunction.Average
Note that Application.
can be omitted. The following function SumAvg that calculates sum of two averages of two input ranges.
Function SumAvg(X as Range, Y as Range)
Dim xavg As Double
Dim yavg As Double
xavg = WorksheetFunction.Average(X)
yavg = WorksheetFunction.Average(Y)
SumAvg = xavg + yavg
End Function
Active Objects
ActiveCell refers to the currently selected cell in your Excel workbook. From there, you can add or delete data from the cell. For example,
Sub WorkingActiveCell()
ActiveCell.Delete
ActiveCell.Value = 11
ActiveCell.text = "Helloworld"
End Sub
The final value in the ActiveCell will be Helloworld. This is because you first deleted whatever was in the cell, then put the value 11 into the cell. After which, you overrode the previous value and put in the word Helloworld into the active cell.
The following shows how to display property of active objects. The first line display a message box that tells the address of the active cell, the second one tells the name of active worksheet, and the second line tells the name of the active workbook (the current file name).
MsgBox (ActiveCell.Address)
MsgBox (ActiveSheet.Name)
MsgBox (ActiveWorkbook.Name)
With
Using a With statement allows you to code more efficiently, especially if you have to keep referring to the same object. The following example shows different properties are set for the cells(1,1).
Sub WithExample()
With Cells(1, 1)
.Value = 4
.Interior.Color = RGB(255, 255, 0)
.Font.Color = RGB(0, 255, 0)
End With
End Sub
The code within the With and End With part is applied to the specified cell, which in this case is Cells(1,1).
Charting
For charting in Excel, there are two methods:
- chart sheet and
- embedded chart.
Chart Sheet
Chart sheet is a worksheet that only has chart. It is an object in a workbook.
To create a new chart sheet, we use the command Charts.Add
. Note that this is similar to adding new worksheet command Worksheets.Add
.
Then we need to define data source using .SetSourceData Source:=
.
Finally, we need to tell what kind of chart is plotting .ChartType =
. For example, line chart is xlLine
Sub NewLineChartSheet()
Dim ChartSheet As Chart
Dim Data As Range
Set ChartSheet = Charts.Add
Set Data = Sheets("Sheet1").Range("A1:B3")
With ChartSheet
.SetSourceData Source:=Data
.ChartType = xlLine
End With
End Sub
It is useful to define a chart with name so that we can refer later.
Sub NewNamedChartSheet()
Dim ChartSheet As Chart
Dim Data As Range
Set ChartSheet = Charts.Add
Set Data = Sheets("Sheet1").Range("A1:B30")
With ChartSheet
.SetSourceData Source:=Data
.ChartType = xlLine
.Name = "mychart"
End With
End Sub
The following code changes a property of an existing chartsheet. The following code changes the chart by including additional data.
Sub ChangeChartSheet()
Dim ChartSheet As Chart
Dim Data As Range
Set ChartSheet = Charts("mychart")
Set Data = Sheets("Sheet1").Range("A1:B50")
With ChartSheet
.SetSourceData Source:=Data
End With
End Sub
Embedded Chart
For the chart to be included in a worksheet, we use ChartObjects.Add
instead.
We need to tell which worksheet to place the diagram and the distance from the top and left of spreadsheet as well as width and height
Sub EmbeddedChart()
Dim mychart As Object
Dim Data As Range
Set mychart = Sheets("Sheet1").ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
Set Data = Sheets("Sheet1").Range("A1:B3")
With mychart.Chart
.ChartType = xlLine
.SetSourceData Source:=Data
End With
End Sub
We can give name to the object but not the chart.
Sub EmbeddedNameChart()
Dim mychart As Object
Dim Data As Range
Set mychart = Sheets("Sheet1").ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
Sheets("Sheet1").ChartObjects(1).Name = "mychart"
Set Data = Sheets("Sheet1").Range("A1:B3")
With mychart.Chart
.ChartType = xlLine
.SetSourceData Source:=Data
End With
End Sub
The following code changes a property of an existing embedded chart. The following code changes the chart by including additional data.
Sub ChangeEmbeddedChart()
Dim ChartObj As Object
Set ChartObj = Sheets("Sheet1").ChartObjects("Hello")
With ChartObj.Chart
.SetSourceData Source:=Sheets("Sheet1").Range("A1:D3")
End With
End Sub
Chart Type
Besides line chart, there are many different types of chart. Here are the common types.
Function | Chart Type |
---|---|
xlLine | line chart |
xlColumnClustered | Clustered Column (vertical bar chart) |
xlBarClustered | Clustered bar (horizontal bar chart) |
xlPie | Pie |
xlArea | Area chart (line chart but colored area) |
xlXYScatter | Scatter |
xlRadar | Radar |
xlStockHLC | High-Low-Close |
xlStockOHLC | Open-High-Low-Close (Candle Stick) |
xlStockVHLC | Volume-High-Low-Close |
xlStockVOHLC | Volume-Open-High-Low-Close |
Data Series
To allow for multiple graphics to be plotted, we need to use seriescollection
.
First, to add a new data, we need to say .SeriesCollection.NewSeries
. Then, we can define the name, XValues (x) and Values (y).
Sub NewChartSheetMultiple()
Dim ChartSheet As Chart
Dim Time, Data1, Data2 As Range
Set ChartSheet = Charts.Add
Set Time = Sheets("Sheet1").Range("A1:A5")
Set Data1 = Sheets("Sheet1").Range("B1:B5")
Set Data2 = Sheets("Sheet1").Range("C1:C5")
With ChartSheet
.ChartType = xlLine
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = "Stock 1"
.SeriesCollection(1).XValues = Time
.SeriesCollection(1).Values = Data1
.SeriesCollection.NewSeries
.SeriesCollection(2).Name = "Stock 2"
.SeriesCollection(2).XValues = Time
.SeriesCollection(2).Values = Data2
End With
End Sub
Record Macro
Lastly, to see how to code certain actions in Excel, VBA has this useful function called Record Macro.
To access it, in the Developer Tab, press the Record Macro button.
Whatever you do in Excel from then on will be recorded in a macro, which you can later access. To stop recording, click the button again, which should now say Stop Recording.
Click on the Visual Basic button (access to VBE) to see your recorded actions in code. This is useful if you know what you want to code, and how to do it in Excel, but you do not know how to code it in VBA.
Macro-enable File
Note that when you save your Excel file, always save it in xlsm format (macro enabled worksheet format), otherwise you will not be able to run your macros when you open the file next time!
VBA (Visual Basic for Applications) is a programming language that empowers you to automate almost every in Excel. With VBA, you can refer to the Excel Objects and use the properties, methods, and events associated with them. For example, you can create a pivot table, insert a chart, and show a message box to the user using a macro.
The crazy thing is:
For all the tasks which you perform manually in minutes, VBA can do it in seconds, with a single click, with the same accuracy. Even you can write VBA codes that can run automatically when you open a document, a workbook, or even at a specific time.
Let me show you a real-life example:
Every morning when I go to the office, the first thing I need to do is to create a pivot table for the month-to-date sales and present it to my boss. This includes the same steps, every day. But when I realized that I can use VBA to create a pivot table and insert it in a single click, it saved me 5 minutes every day.
Note: VBA is one of the Advanced Excel Skills.
How VBA Works
VBA is an Object-Oriented Language and as an object-oriented language, in VBA, we structure our codes in a way where we are using objects and then defining their properties.
In simple words, first, we define the object and then the activity which we want to perform. There are objects, collections, methods, and properties which you can use in VBA to write your code.
[icon name=”bell” class=””] Don’t miss this: Let’s say you want to tell someone to open a box. The words you will use would be “Open the Box”. It’s plain English, Right? But when it comes to VBA and writing a macro this will be:
Box.Open
As you can see, the above code is started with the box which is our object here, and then we have used the method “Open” for it. Let’s go a bit specific, let say if you want to open the box which is RED in color. And for this the code will be:
Boxes(“Red”).Open
In the above code, boxes are the collection, and open is the method. If you have multiple boxes we are defining a specific box here. Here’s another way:
Box(“Red”).Unlock = True
In the above code, again boxes are the collection, and Unlock is the property that is set to TRUE.
What is VBA used for in Excel?
In Excel, you can use VBA for different things. Here are a few:
- Enter Data: You can enter data in a cell, range of cells. You can also copy and paste data from one section to another.
- Task Automation: You can automate tasks that want you to spend a lot of time. The best example I can give is using a macro to create a pivot table.
- Create a Custom Excel Function: With VBA, you can also create a Custom User Defined Function and use it in the worksheet.
- Create Add-Ins: In Excel, you can convert your VBA codes into add-ins and share them with others as well.
- Integrate with other Microsoft Applications: You can also integrate Excel with other Microsoft applications. Like, you can enter data into a text file.
Excel Programming Fundamentals
A procedure in VBA is a set of codes or a single line of code that performs a specific activity.
- SUB: Sub procedure can perform actions but doesn’t return a value (but you can use an object to get that value).
- Function: With the help of the Function procedure, you create your function, which you can use in the worksheet or the other SUB and FUNCTION procedures (See this: VBA Function).
2. Variables and Constants
You need variables and constants to use values in the code multiple times.
- Variable: A Variable can store a value, it has a name, you need to define its data type, and you can change the value it stores. As the name suggests, “VARIABLE” has no fixed value. It is like a storage box that is stored in the system.
- Constant: A constant also can store a value, but you can’t change the value during the execution of the code.
3. Data Types
You need to declare the data type for VARIABLES and CONSTANTS.
When you specify the data type for a variable or a constant, it ensures the validity of your data. If you omit the data type, VBA applies the Variant data type to your variable (it’s the most flexible), VBA won’t guess what the data type should be.
Tip: VBA Option Explicit
4. Objects, Properties, and Methods
Visual Basic for Applications is an Object-Oriented language, and to make the best out of it; you need to understand Excel Objects.
The workbook you use in Excel has different objects, and with all those objects, there are several properties that you can access and methods that you can use.
5. Events
Whenever you do something in Excel, that’s an event: enter a value in a cell, insert a new worksheet, or insert a chart. Below is the classification of events based on the objects:
- Application Events: These are events that are associated with the Excel application itself.
- Workbook Events: These are events that are associated with the actions that happen in a workbook.
- Worksheet Events: These events are associated with the action that happens in a worksheet.
- Chart Events: These events are associated with the chart sheets (which are different from worksheets).
- Userform Events: These events are associated with the action that happens with a user form.
- OnTime Events: OnTime events are those which can trigger code at a particular point in time.
- OnKey Events: OnKey events are those which can trigger code when a particular key is pressed.
6. Range
The range object is the most common and popular way to refer to a range in your VBA codes. You need to refer to the cell address, let me tell you the syntax.
Worksheets(“Sheet1”).Range(“A1”)
7. Conditions
Just like any other programming language, you can also write codes to test conditions in VBA. It allows you to do it in two different ways.
- IF THEN ELSE: It’s an IF statement that you can use to test a condition and then run a line of code if that condition is TRUE. You can also write nesting conditions with it
- SELECT CASE: In the select case, you can specify a condition and then different cases for outcomes to test to run different lines of code to run. It’s a little more structured than the IF statement.
8. VBA Loops
You can write codes that can repeat and re-repeat an action in VBA, and there are multiple ways that you can use to write code like this.
- For Next: The best fit for using For Next is when you want to repeat a set of actions a fixed number of times.
- For Each Next: It’s perfect to use when you want to loop through a group of objects from a collection of objects.
- Do While Loop: The simple idea behind the Do While Loop is to perform an activity while a condition is true.
- Do Until Loop: In the Do Until, VBA runs a loop and continues to run it if the condition is FALSE.
9. Input Box and Message Box
- Input Box: The input Box is a function that shows an input box to the user and collects a response.
- Message Box: Message Box helps you show a message to the user but, you have an option to add buttons to the message box to get the response of the user.
10. Errors
Excel has no luck when it comes to programming errors, and you have to deal with them, no matter what.
- Syntax Errors: It’s like typos that you do while writing codes, but VBA can help you by pointing out these errors.
- Compile Errors: It comes when you write code to perform an activity, but that activity is not valid.
- Runtime Errors: A RUNTIME error occurs at the time of executing the code. It stops the code and shows you the error dialog box.
- Logical Error: It’s not an error but a mistake while writing code and sometimes can give you nuts while finding and correcting them.
Write a Macro (VBA Program) in Excel
I have a strong belief that in the initial time when someone is starting programming in Excel, HE/SHE should write more and more codes from scratch. The more codes you write from scratch, the more you understand how VBA works.
But you need to start with writing simple codes instead of jumping into complex ones. That’s WHY I don’t want you to think about anything complex right now.
You can even write a macro code to create a pivot table, but right now, I don’t want you to think that far. Let’s think about an activity that you want to perform in your worksheet, and you can write code for it.
- Go to the Developer Tab and open the Visual Basic Editor from the “Visual Basic” button.
- After that, insert a new module from the “Project Window” (Right-click ➢ Insert ➢ Module).
- After that, come to the code window and create a macro with the name “Enter Done” (we are creating a SUB procedure), just like I have below.
- From here, you need to write a code which we have just discussed above. Hold for second and think like this: You need to specify the cell where you want to insert the value and then the value which you wish to enter.
- Enter the cell reference, and for this, you need to use RANGE object and specify the cell address in it, like below:
- After that, enter a dot, and the moment you add a dot, you’ll have a list of properties that you can define and activities that you can do with the range.
- From here, you need to select the “Value” property and set the text which you want to insert in the cell “A1” and when to do it, your code with look something like below.
- Finally, above the line of code, enter the text (‘this code enters the value “Done” in the cell A5). It’s a VBA Comment that you can insert to define the line of code that you have written.
Sub Enter_Done()
'this code enters the value “Done” in the cell A5
Range("A1").Value = "Done"
End Sub
Let’s understand this…
You can split this code into two different parts.
- In the FIRST part, we have specified the cell address by using the RANGE object. And, to refer to a cell using a range object you need to wrap the cell address with double quotes (you can also use square brackets).
- In the SECOND part, we have specified the value to enter into the cell. What you have done is, you have defined the value property for cell A5 by using “.Value”. After that, the next thing that you have specified is the value against the value property. Whenever you are defining a value (if it’s text), you need to wrap that value inside double quotation marks.
Here I have listed some of the most amazing tutorials (not in any particular sequence) that can help you learn VBA in NO TIME.