Vba library for excel

Время на прочтение
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 IntegerAs 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, название и цена) и есть две вложенные группы, к которым она принадлежит (тип и производитель). Более того, эти строки отсортированы. Пока мы забудем про пропуски перед началом новой группы — так будет проще. Я предлагаю такой алгоритм:

  1. Считали группы из очередной строки.
  2. Пробегаемся по всем группам в порядке приоритета (вначале более крупные)
    1. Если текущая группа не совпадает, вызываем процедуру AddGroup(i, name), где i — номер группы (от номера текущей до максимума), name — её имя. Несколько вызовов необходимы, чтобы создать не только наш заголовок, но и всё более мелкие.
  3. После отрисовки всех необходимых заголовков делаем еще одну строку и заполняем её данными.

Для упрощения работы рекомендую определить следующие функции-сокращения:

Function GetCol(Col As IntegerAs String
    GetCol = Chr(Asc("A") + Col)
End FunctionFunction GetCellS(Sheet As String, Col As Integer, Row As IntegerAs Range
    Set GetCellS = Sheets(Sheet).Range(GetCol(Col) + CStr(Row))
End FunctionFunction GetCell(Col As Integer, Row As IntegerAs 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) — тут скобки нужны постоянно.


Libraries add pre-defined code structures (such as functions, subroutines among others) in a simple and easy way.

In the VBA context, a library usually allows access to new objects and functions.


Standard Libraries

Libraries that are enabled by default when opening Excel:

Standard Libraries

  1. Excel – This is a collection of classes available in Excel, allowing you to work with worksheets objects E.g. workbooks, spreadsheets, ranges, etc…
  2. Office – It is a generic class collection for all Office suite applications, allowing you to work with Office objects in general E.g. command bar, help, etc…
  3. stdole – It is the standard collection of the OLE class, it allows exchange of information between applications
  4. VBA – It is the class collection that allows functions to be used E.g. MsgBox, InputBox, string functions, etc…
  5. VBAProject – It is the local collection for the active workbook, (E.g. spreadsheets, users, etc…)

Class: is what defines the structure of a given object (E.g. for class Range we have objects like Range(«A1»), Range(«C2:B5»), and so on).


Enabling Libraries

To access, enable and disable libraries in VBA:

  1. In Excel, open the VBE (Alt+F11)
  2. On the Menu Bar, click Tools
  3. Select References… (the References – VBAProject dialog box will be displayed)
  4. Select the desired libraries
  5. Click OK

Enabling Libraries

To add a library that is not in the list, use the button and select the file of the new library.

Enabling additional libraries allows you to develop codes that communicate with other applications and processes. E.g. Word, Outlook, DAO (Data Access Objects), ADOdb (Active Data Objects database), etc…

When we refer to a library in the code but forget to enable it, the following error message is displayed:

Librarie Not Defined


Object Browser

The Object Browser allows you to view the list of all the different objects, methods, and properties of the enabled libraries.

To search the libraries:

  1. Click on the Object Browser icon on the toolbar ()
  2. Select the library you want to view on the dropdown menu
  3. Navigate the library

Object Browser

When in doubt, the Microsoft Help button () can elucidate the utility of the selected element.


VBA Early Binding vs Late Binding

You can use structures from a library without enabling it. This procedure is called Late Binding.

Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")

Usually for the Late Binding a variable is declared as an object and later associated with CreateObject.

When we enable a library to access its structures we are performing what is called Early Binding.

Dim OutApp As New Outlook.Application

In the example case the Outlook library was enabled ().


Early & Late Binding Differences

Early: From the point of view of code development and performance time, Early Binding is more suitable because it allows you to use Excel intellisense ( + ) as well as the library object browser.

Late: Regarding compatibility errors, mainly due to the use of different versions of Excel (which changes the version of the libraries), Late Binding is more indicated.

Intellisense: is an aid, mainly to autocomplete the code, with useful information ( + ).

Intellisense

So, to gain practice with the libraries, try to write the code with Early Binding and later change it into Late Binding.



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

1
branch

0
tags


Code

  • Use Git or checkout with SVN using the web URL.

  • Open with GitHub Desktop

  • Download ZIP

Latest commit

Files

Permalink

Failed to load latest commit information.

Type

Name

Latest commit message

Commit time

Excel Macro VBA Library

This repository is created to build a library of reusable VBA / Macro modules and functions for Microsoft Excel.

Right click to import the bas file as a new code module in excel vba.

Included generic funtions and subroutines:

1) WorksheetExists

2) CopyRowAboveAndInsert

3) ProperX

'This is exactly like the PROPER function but works also in VBA
'It makes the first letter in the input string capital

4) Email_part

'Returns the selected part of an email adress

5) current_user

'gets the user id of the currently logged on active user

6) current_user_domain

'gets the user domain of the currently logged on active user

7) get_user_info

'this function queries active directory for information about a user and returns one value at a time

8) get_user_id_from_distinguishedname

'this function queries active directory for the user id of a user with a certain distinguished name

9) get_user_id_from_email

'This functions is for when the LDAP query returns the Dist name but we want the ID

10) ReturnNthPartOfString

'Splits a delimited string and returns the Nth part

11) RegisterDescriptionForUserDefinedFunction()

' This function is only needed to run once to register help text and category for a user defined function

12) Custom_GetLastRow

13) Custom_SetRowHeightSheet

'Adjust row height for the entire sheet.

14) Custom_CopyRenameSheet

' Sub routine to copy a source sheet to a new sheet and to rename the new sheet.

15) Custom_NewRenameSheet

' Sub routine to create a new sheet and to rename the new sheet.

16) Custom_CopyPasteColumn

' Sub routine to copy a column at position 'columnReferenceNumber' and insert it at position 'pastePositionReference'.

17) Custom_InsertRenameColumn

' Sub routine to insert a new column at column position 'targetColumnReference' of the sheet 'targetSheet', set width as 'targetColumnWidth' and set name as 'targetColumnName'.

18) Custom_AddComment

' Add a comment to a cell.

19) Custom_RearrangeColumns

' Sub Routine to re-arrange columns from one sheet to another.  
' A continuous column sequencing and definitions of order of rearrangement in the 'formatReferenceSheetName' is expected for this sub routine to work properly.
' Refer to "FR_1" sheet within the excel file "Excel_Reference_Sheet.xlsx" in the GitHub repository "excel-macro-vba-library".

20) Custom_EnterFormulaAndFillDown

' This sub routine enters a formula text 'formulaText' in a column's first cell (defined by 'targetSheet', 'columnReference' and 'rowOffset').  
'The formula will be populated down to 'lastRow'.  Furthermore, the function will replace the cells involved with their values and remove the formula definitions after the fill down has been completed.

21) Custom_ConvertNumberSavedAsText

' Sub routine to convert number stored as text to number.

22) Custom_DeleteColumn

' Delete the 'targetColumn' in 'targetSheet'.

23) Custom_CreatePivotTable

' Sub routine to create and design a Pivot Table as per definition in the Reference sheet formatReferenceSheet.
' Refer to "PR_1" and "PR_2" sheet within the excel file "Excel_Reference_Sheet.xlsx" in the GitHub repository "excel-macro-vba-library".

24) Custom_PivotTableAddField

' Create a Page Field (Report Filter) in the pivot table 'pivotTableName' in sheet 'pivotTableTargetSheet'.

25) Custom_PivotTableAddDataField

' Create a DataField in the pivot table 'pivotTableName' in sheet 'pivotTableTargetSheet', with name as 'dataFieldName' and with format 'dataFieldFormat'.

26) Custom_SetColumnNumberFormat

' Set the number format of a particular Column.

27) Custom_SortSheetByColumn

' Sort the entire sheet 'targetSheet' by the 'key1ColumnReference' in the order indicated by 'order1Reference'

28) Custom_RemoveDuplicates

' Remove all rows where the Column referred by 'indexColumnReference' has duplicate values.

29) Custom_FreezeView

' Freeze the view of the targetSheet.  The Split will be made at columnSplitLength and rowSplitLength.

30) Custom_DeleteSheet

' Delete targetSheet.

31) Custom_ColorRange

' Enter color into the range.
    
32) Custom_HideSheet(targetSheet As Worksheet)

' Hide Sheet.

33) Custom_ColumnFilter

' Enable filter on a column of the targetSheet.  Filter for string value criteriaString.

34) Custom_ReleaseFilter

' Remove all filters from the targetSheet.

35) Custom_DeleteVisibleRows

' Delete all Visible Rows in the targetSheet.  This should be used after filtering the current sheet for the information you would want to have deleted.    

36) Custom_SetColumnWidthSheet

'  Adjust column width for the entire sheet.

37) Custom_InsertRenameColumn

AutoMacro

Ready-to-use VBA Code

See Pricing

What is AutoMacro?

AutoMacro is an add-in for VBA that installs directly into the Visual Basic Editor. It comes loaded with code generators, an extensive code library, the ability to create your own code library, and many other time-saving tools and utilities that add much needed functionality to the outdated VBA Editor.

AutoMacro does not need to be installed on a computer for the generated code to run. Once the code is generated, anyone can use it!

automacro

Code Builders

  • Generate VBA code from scratch
  • Visual interfaces

Learn More

Code Library

  • Hundreds of ready-to-use code examples
  • Save your own code

Keep Reading…

Coding Tools

  • Tools for Formatting and Navigating
  • Excel Model Debugger & More

Learn More

VBA Code Library

AutoMacro’s code library contains hundreds of commonly used code fragments for Excel, Access, Outlook, Word, and PowerPoint. As well as the ability to add your own code to the library.

Simply select the code from AutoMacro’s menu and it will be inserted directly into your module.

Compatible with

access vba code library

Loops Code Library

Loops and If statements are essential components of VBA programming . With the Loop Code Generator you can generate conditional loops with a few simple clicks.

Simply select the object (ex. rows) then the action (ex. delete) and last the criteria (ex. blank rows).

You can add additional actions or criteria and «match» the actions to the criteria, allowing you to perform different actions based on which criteria is met.

vba code generator

vba objects code

Object Code Library

Easily manipulate objects like Ranges, Columns, Rows, Sheets, and Workbooks. Great for Beginners or for editing code from the loop code generator.

Learn More

Functions and Procedures

Professionally developed functions and procedures a mouse-click away.

vba code library functions

Code for Access, Outlook, Word, and PowerPoint

In addition to Excel, AutoMacro has code examples for Access, Outlook, Word, and PowerPoint.

access vba code library outlook vba code library word vba code library vba powerpoint code library

Custom Code Library

Create your own VBA Code Library. Organize code into folders and access all code via keyboard shortcuts.

Share custom code folders with co-workers.

Join the Thousands of Professionals Who Use AutoMacro

«I use it almost every day. A great tool for getting things done, but also a great tool for learning how to do things! This is one purchase this year I have no regrets about.»

Galen — USA

TrustSpot Verified

4.7 Average Rating!

See Pricing

Other AutoMacro Features

Code Generators

Code Generators build code from scratch via visual interfaces.

No coding knowledge required!

Learn More

vba code builder

Coding Tools

VBA Coding tools to improve the out of date Visual Basic Editor.

Speed up your workflow with tools to navigate, debug, format and more.

Learn More

Beginner

1 User — 1 PC

  • Interactive VBA Tutorial
  • 100+ ready-to-use code examples
  • Procedure, Loops, & Copy Paste Builders
  • All other code generators
  • Coding tools
  • Create your own code library
  • Transfer Activations to other PCs
  • Access to new features & updates

One-time fee

Click for Alternative Payment Options

Money back guaranteed
TrustSpot Verified

Upgrade Anytime!

Developer

1 User — 3 PCs

  • Interactive VBA Tutorial
  • Hundreds of ready-to-use code examples
  • Procedure, Loops, & Copy Paste Builders
  • All other code generators
  • Coding tools
  • Create your own code library
  • Transfer Activations to other PCs
  • Access to new features & updates

One-time fee

Click for Alternative Payment Options

Money back guaranteed
TrustSpot Verified

Upgrade Anytime!

Developer+

1 User — 3 Transferable PCs & Updates

  • Interactive VBA Tutorial
  • Hundreds of ready-to-use code examples
  • Procedure, Loops, & Copy Paste Builders
  • All other code generators
  • Coding tools
  • Create your own code library
  • Transfer activations to other PCs
  • Access to new features & updates

One-time fee + $20 Annual

Click for Alternative Payment Options

Money back guaranteed
TrustSpot Verified

AutoMacro has been used by employees of these organizations. These organizations do not endorse, approve, sponsor, or otherwise have any affiliation with this website, Spreadsheet Boot Camp LLC, or ToolFive Software LLC.

FAQ and Other Information

What is your refund policy?

We have a 30-day, no-questions-asked, 100% money-back guarantee. If you’re unsatisfied for any reason, let us know and we will refund your order!

Can I try AutoMacro before I buy?

Can I install AutoMacro on my Work Computer?

Yes! AutoMacro works in many corporate environments. It was designed to be as unobtrusive as possible and should install without the need for «admin privileges».

Will AutoMacro work on my system?

AutoMacro is compatible with all versions of Microsoft Office for PCs.

32-bit or 64-bit
Office 2003, 2007, 2010, 2013, 2016, 2019, Office 365, etc.
All Versions of Windows
Surface Pro
AutoMacro is not compatible with Mac operating systems. However, some Mac users running Windows OS are able to use AutoMacro.

If you have doubts, please try the download link above to check.

AutoMacro is not compatible with Citrix environments.

Can I deduct this purchase on my taxes?

See this page from the IRS on Employee Business Expenses.

Can I use on more than one computer?

The Beginner version entitles you to a single-use license code valid for 1 computer. The Developer version is valid for 3 computers. The Developer+ allows you to transfer activations between PCs, so that AutoMacro can be activated on any 3 PCs at one time.

Does AutoMacro work with PowerPoint, Word, or Access?

Yes! AutoMacro functions in any program with the Visual Basic Editor.

Specific code examples were developed for Excel, Access, Outlook, Word, and PowerPoint.

Visit AutoMacro’s FAQ Page

Join the Thousands of Professionals Who Use AutoMacro

«Great product, haven’t stopped using it since I purchased it. It doesn’t just write your code, it teaches as you go!»

Tony D — United Kingdom

TrustSpot Verified

4.7 Average Rating!

See Pricing

Steve Rynearson:
Creator of AutoMacro

Over the years, I’ve spent countless hours searching online for example code and adapting that code to my needs.

I often found myself clicking the same links and copying the same code. I thought there has to be a better way!

AutoMacro eliminates much of this need to search online for code. Instead simply use the menus to select pre-built code or use the builders to generate code for your exact needs.

Additionally, the coding tools will save you time and help you develop more professional looking code.

For anyone coding VBA, AutoMacro is a life-saver. You’ll code much faster, develop more professional code, and learn VBA much faster (if you’re not already an expert).

VBA Libraries

Libraries are used to access functionality outside of what VBA can do on its own. There are a number of VBA libraries provided by the Windows operating system, Office applications, and other software installed by the user. Libraries are often used to control a specific application or access classes which serve specific purposes. Libraries can be used to write VBA programs that utilize multiple applications, access the user’s file system, manipulate text files and databases, get information from the internet, and more.

Set Library References

Setting a reference to a library allows a VBA project to access the members of the library directly. Setting a reference allows the VBA compiler and the Visual Basic Editor to see the members of a library. Setting a reference allows for early-binding of object variables, enables intellisense, and makes the library visible in the Object Browser. To set a reference to a library navigate to Tools → References in the Visual Basic Editor and check the library and click Ok. Members of a library can be accessed without a reference by using late-binding (declaring an object variable with the generic Object type and using the CreateObject function with the class’s ProgID). Early-binding vs late-binding is discussed in the Objects section.

Set Reference

Fully Qualified Identifiers

When using libraries, be sure to use the fully qualified names for classes, variables, and procedures to avoid naming collisions. There are times when a library contains an identifier that is the same as another identifier in VBA or another library. If the name is not fully qualified, VBA will not know which identifier is being referred to and errors can occur. To fully qualify an identifier’s name include the library of origin.

Public Sub Example()

    'References set to Excel object library and Word object library

    Dim ExcelApp As Excel.Application
    Dim WordApp  As Word.Application

    Set ExcelApp = Excel.Application
    Set WordApp = Word.Application

End Sub

Exploring Libraries

To explore the contents of a library in detail set a reference to the library and use the Object Browser to view the library’s members.

Search and Browse Specific Libraries

Specific libraries can be browsed and searched by selecting the library from the library drop-down.

Object Browser Select Scripting Library

View Class Members

Select an item in the Classes section and view its members in the Members section.

Object Browser Dictionary

Search

Use the search bar to search for specific text related to a class or member. Select an item in the Search Results to view its members in the members section.

Object Browser Search TextStream

Important Libraries

There are a number of important libraries which are very commonly used and are often necessary for accomplishing tasks in VBA.

Name: Scripting
Description: Microsoft Scripting Runtime
FullPath: C:WindowsSystem32scrrun.dll
GUID: {420B2830-E718-11CF-893D-00A0C9054228}
Use Cases: File System, Text Files, Dictionary Class
Name: ADODB
Description: Microsoft ActiveX Data Objects 6.1 Library
FullPath: C:Program FilesCommon FilesSystemadomsado15.dll
GUID: {B691E011-1797-432E-907A-4D8C69339129}
Use Cases: Databases, Text Files
Name: MSHTML
Description: Microsoft HTML Object Library
FullPath: C:WindowsSystem32mshtml.tlb
GUID: {3050F1C5-98B5-11CF-BB82-00AA00BDCE0B}
Use Cases: HTML, DOM
Name: SHDocVw
Description: Microsoft Internet Controls
FullPath: C:WindowsSystem32ieframe.dll
GUID: {EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}
Use Cases: IE Automation
Name: WinHttp
Description: Microsoft WinHTTP Services, version 5.1
FullPath: C:Windowssystem32winhttpcom.dll
GUID: {662901FC-6951-4854-9EB2-D9A2570F2B2E}
Use Cases: HTTP Requests
Name: MSXML2
Description: Microsoft XML, v3.0 | v6.0
FullPath: C:WindowsSystem32msxml3.dll | C:WindowsSystem32msxml6.dll
GUID: {F5078F18-C551-11D3-89B9-0000F81FE221}
Use Cases: XML, HTTP Requests
Name: Shell32
Description: Microsoft Shell Controls And Automation
FullPath: C:WindowsSysWOW64shell32.dll
GUID: {50A7E9B0-70EF-11D1-B75A-00A0C90564FE}
Use Cases: Shell, Zip Files, File System
Name: IWshRuntimeLibrary
Description: Windows Script Host Object Model
FullPath: C:WindowsSystem32wshom.ocx
GUID: {F935DC20-1CF0-11D0-ADB9-00C04FD58A0B}
Use Cases: Shell, Shortcuts, File System, Network, Registry
Name: VBScript_RegExp_55
Description: Microsoft VBScript Regular Expressions 5.5
FullPath: C:WindowsSystem32vbscript.dll3
GUID: {3F4DACA7-160D-11D2-A8E9-00104B365C9F}
Use Cases: Regular Expressions
Name: VBIDE
Description: Microsoft Visual Basic for Applications Extensibility 5.3
FullPath: C:Program Files (x86)Common FilesMicrosoft SharedVBAVBA6VBE6EXT.OLB
GUID: {0002E157-0000-0000-C000-000000000046}
Use Cases: Visual Basic Editor, Project References
Name: mscorlib
Description: mscorlib.dll
FullPath: C:WindowsMicrosoft.NETFramework64v4.0.30319mscorlib.tlb
GUID: {BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}
Use Cases: ArrayList

Microsoft Office Applications

To work with more than one Office application in a single VBA program it is helpful to set references to all Office applications being used.

Name: Access
Description: Microsoft Access 16.0 Object Library
FullPath C:Program FilesMicrosoft OfficerootOffice16MSACC.OLB
GUID: {4AFFC9A0-5F99-101B-AF4E-00AA003F0F07}
Name: Excel
Description: Microsoft Excel 16.0 Object Library
FullPath C:Program FilesMicrosoft OfficerootOffice16EXCEL.EXE
GUID: {00020813-0000-0000-C000-000000000046}
Name: Outlook
Description: Microsoft Outlook 16.0 Object Library
FullPath C:Program FilesMicrosoft OfficerootOffice16MSOUTL.OLB
GUID: {00062FFF-0000-0000-C000-000000000046}
Name: PowerPoint
Description: Microsoft PowerPoint 16.0 Object Library
FullPath C:Program FilesMicrosoft OfficerootOffice16MSPPT.OLB
GUID: {91493440-5A91-11CF-8700-00AA0060263B}
Name: Publisher
Description: Microsoft Publisher 16.0 Object Library
FullPath C:Program FilesMicrosoft OfficerootOffice16MSPUB.TLB
GUID: {0002123C-0000-0000-C000-000000000046}
Name: Word
Description: Microsoft Word 16.0 Object Library
FullPath C:Program FilesMicrosoft OfficerootOffice16MSWORD.OLB
GUID: {00020905-0000-0000-C000-000000000046}
Name: Visio
Description: Microsoft Visio 16.0 Type Library
FullPath C:Program FilesMicrosoft OfficerootOffice16VISLIB.DLL
GUID: {00021A98-0000-0000-C000-000000000046}

Adobe Acrobat

The Adobe Acrobat Library can be used to automate the Adobe Acrobat application and work with PDF files. Adobe Acrobat must be purchased from Adobe and installed in order for the VBA libraries to be available.

Name: Acrobat
Description: Adobe Acrobat 10.0 Type Library
FullPath: C:Program Files (x86)AdobeAcrobat 2017Acrobatacrobat.tlb
GUID: {E64169B3-3592-47D2-816E-602C5C13F328}
Name: AFORMAUTLib
Description: AFormAut 1.0 Type Library
FullPath: C:Program Files (x86)AdobeAcrobat Reader DCReaderplug_insAcroForm.api
GUID: {7CD06992-50AA-11D1-B8F0-00A0C9259304}

Micro Focus Reflection

The Micro Focus Reflection libraries can be used to automate tasks in the Micro Focus Reflection application. Micro Focus Reflection Desktop 16.1 must be purchased and installed in order for the libraries to be available.

Name: Attachmate_Reflection_Objects
Description: C:Program Files (x86)Micro FocusReflectionAttachmate.Reflection.Objects.tlb
GUID: {6857A7F4-4CDE-43F2-A7B1-CB18BA8AA35F}
Name: Attachmate_Reflection_Objects_Emulation_IbmHosts
Description: C:Program Files (x86)Micro FocusReflectionAttachmate.Reflection.Objects.Emulation.IbmHosts.tlb
GUID: {0D5D17DF-B511-4BE5-9CD0-10DE1385229D}
Name: Attachmate_Reflection_Objects_Emulation_OpenSystems
Description: C:Program Files (x86)Micro FocusReflectionAttachmate.Reflection.Objects.Emulation.OpenSystems.tlb
GUID: {3BA4C5BF-F24A-4BE4-8BAB-8BD78C2FABDE}
Name: Attachmate_Reflection_Objects_Framework
Description: C:Program Files (x86)Micro FocusReflectionAttachmate.Reflection.Objects.Framework.tlb
GUID: {88EC0C50-0C86-4679-B27D-63B2FCF1C6F4}

Programmatically Work With Project References

To programmatically work with project references use the Microsoft Visual Basic for Applications Extensibility 5.3 Library (VBIDE).

'In Immediate Window:

?SetProjectReferenceByFilePath("C:WindowsSystem32scrrun.dll")

PrintProjectReferences ThisWorkbook.VBProject

Option Explicit

Public Sub SetProjectReferenceByFilePath(FilePath As String)

    'Sets Project Reference

    Dim VBProj    As Object 'VBIDE.VBProject
    Dim Refs      As Object 'VBIDE.References
    Dim Ref       As Object 'VBIDE.Reference
    Dim RefFound  As Boolean

    Set VBProj = ThisWorkbook.VBProject
    Set Refs = VBProj.References

    For Each Ref In Refs
        If Ref.FullPath = FilePath Then
            RefFound = True
            Exit For
        End If
    Next Ref

    If Not RefFound Then
        VBProj.References.AddFromFile FilePath
    End If

End Sub

Public Sub PrintProjectReferences(Proj As Object)
                                 'Proj As VBIDE.VBProject

    Dim Ref As Object 'VBIDE.Reference

    For Each Ref In Proj.References
        With Ref
            Debug.Print "'''''''''''''''''''''''''''''''''''''''''''''''''"
            Debug.Print "Name: " & .Name
            Debug.Print "Major Version: " & .Major
            Debug.Print "Minor Version: " & .Minor
            Debug.Print "Description: " & .Description
            Debug.Print "FullPath: " & .FullPath
            Debug.Print "GUID: " & .GUID
            Debug.Print "Builtin: " & .BuiltIn
            Debug.Print "Type: " & .Type
            Debug.Print "'''''''''''''''''''''''''''''''''''''''''''''''''"
        End With
    Next Ref

End Sub

Понравилась статья? Поделить с друзьями:
  • Vba for excel select cell
  • Vba insert formula in excel
  • Vba for excel reference
  • Vba in word template
  • Vba for excel online