Библиотеки vba для excel


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

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

  • Download source files — 17.1 Kb
  • Download demo project — 55.8 Kb

Sample Image - Excel_VBA_Library.jpg

Introduction

After the arrival of VSTO, VBA development is almost outdated. However, to support Office 2000, developers still need a library to easily code a VBA based solution. Excel VBA Library could be used in order to use Excel as database tables to INSERT, UPDATE and SELECT. There are also other libraries to simplify Excel VBA developer life a bit. I hope it will be of some help.

List of libraries

  • ACell: Use this library to obtain row, column or cell address for current row.
  • AComboBox: Use this library to simplify loading of ComboBox and ListBox.
  • AConst: Defining your constants at one place could be handy, no matter how small your project is.
  • ALog: Use this library to write a log of a Excel sheet by the name of «Log». For background processes, this log could be very helpful.
  • AMsgForm: Use this library instead of MsgBox to provide consistent application name and message formatting in your VBA solutions.
  • AOptions: Use this library to get/set end user preferences to an Excel sheet named «Option«.
  • ARange: Use this library to obtain valid range string or range object from a given row, column.
  • ASQL: Use this library to use the Excel sheet as a database table. This library could simplify INSERT, UPDATE, SELECT in an Excel sheet.
  • AStr: Use this library for string manipulation and formatting.
  • ATable: Use this library to make use of an Excel worksheet as a database table. Make sure that the first row of the sheet contains column names. This library simplifies table based worksheet tasks.

How To Use Code

  • Create an Excel sheet.
  • Open VBA editor by pressing Alt+F11.
  • Drag Drop to include all the VBA library module files in workbook.
  • Place buttons on sheet and assign the following macros to each button.
    Sub Button1_Click()
        AMsgForm.Show "Use ALog library to write information in Log. _
                        A info Log is written."
        ALog.WriteErr "Use ALog library to write information in Log"
    
        AMsgForm.Show "Use ALog library to write errors in Log. _
                        An error Log is written."
        ALog.WriteInfo "Use ALog library to write errors in Log"
    End Sub
    
    Sub Button3_Click()
        AMsgForm.Show "You could have consistent messages with _
                            AMsgForm library"
    
        AMsgForm.ShowErr "& Errors. This is an error message"
    End Sub
    
    Sub Button5_Click()
        AMsgForm.Show "Use AOption library to get/set user preferences."
    
        AMsgForm.Show AOptions.StrGet(OptionE.Option1, "Not found")
    End Sub
    
    Sub Button7_Click()
        Dim rs
    
        AMsgForm.Show "Use ASQL library to SELECT, INSERT, UPDATE Excel sheet. _
         Now count of cities will be selected in City sheet."
    
        Set rs = ASQL.Run("City")
    
        AMsgForm.Show rs.RecordCount
    End Sub
    
    Sub Button8_Click()
        AMsgForm.Show "Use AStr  for string manipulation and formatting."
    
        AMsgForm.Show AStr.Quote("Quote a string in VBA always ends up _
        in dirty and less maintainable code. But its easy with AStr.Quote")
    
        AMsgForm.Show AStr.Bracket("To bracket use AStr.Bracket")
    End Sub

Software engineer developing solutions using Microsoft technologies.

excel vba examples free download

companies

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.

About the Add-in

Our free VBA add-in installs directly into the VBA Editor (see above).

It contains 150 ready-to-use VBA Macro code examples for Excel. Simply click your desired code example and it will insert directly into your module:

vba add-in code examples

Download

Click the download button to download our free VBA add-in for Excel!

Important! Read the Walkthrough below. It contains important information.

Walkthrough

The macro code examples add-in was designed entirely with VBA. This can be convenient because you don’t need to install anything, but VBA has limitations. As a result of these limitations, the add-in will stop functioning periodically (note: this happens when VBA «loses focus», often as a result of code errors).

To help, we built in a «reset» button:

vba excel download

To activate the reset, go to Excel and click the AutomateExcel.com Ribbon > Restore VBA Add-in.

If you find the add-in useful, you’ll love our premium VBA add-in (more information below). The premium add-in is not built with VBA and doesn’t require any resets. It has many more (better organized) code fragments, VBA code generators, the ability to save your own code, and much more….

Installation

1. Download the file above

2. Follow these directions to install an Excel Add-in.

3. If you encounter an error «Trust access to the VBA project object model is disabled» then you must update the following settings

VBA Add-in FAQs

How to download VBA For Excel?

All versions of Excel already come with VBA installed. Use shortcut ALT + F11 to open the VBA Editor.

How to install Excel Add-ins?

Make sure the Developer Ribbon is installed. Then go to Developer > Excel Add-ins > Browse to select and install your add-in.

What is the VBA Code Examples Add-in?

The VBA Code examples add-in is a free add-in for Excel / VBA that comes with 150+ ready-to-use VBA code examples & macros.

AutoMacro — The Ultimate VBA Add-in

AutoMacro is an add-in that installs directly into the Visual Basic Editor:

excel vba add ins download

The add-in comes loaded with code generators, hundreds of macro code examples, the ability to create your own code library, and other time-saving tools.

Join the Hundreds 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

AutoMacro Features

Code Generators

Code Generators build code from scratch via visual interfaces!

vba code builder

vba code library builder

Code Library

300 Ready-to-use code examples & VBA macros.

Save your own frequently used code and share with team members.

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.

vba code tools

vba interactive tutorial

VBA Tutorial

Our premium VBA add-in contains a free VBA tutorial.

Just download AutoMacro and you’ll have access to the tutorial.

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

Customer Reviews

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 Hundreds 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

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 is the ultimate VBA Code Helper! It eliminates much of the 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).

Коллекция макросов Excel VBA

Формат DBF, конечно, давно уже умер, но Федеральные службы РФ все еще охотно
его используют. Например, ФСФМ (ФинМониторинг) требует отправлять ему файлы
«в формате DBF», где 244 поля, и некоторые из них — типа C 254. Большинство
древних утилиток для обработки DBF сходят с ума от таких объемов, а Excel
никогда не сохранял требуемую структуру, более того — еще и даты часто
коверкает. Так что даже открыть и посмотреть такой файл — целая проблема,
а уж подкорректировать и сохранить как предписано — еще сложнее.

В итоге была написана эта программа для ручной обработки DBF, ни на кого не
надеясь. Вернее, это была написана когда-то целая система Банк-Клиент на VBA
Excel, и коллекция разных макросов из нее все еще на что-то годится, гибко
обрабатывая типично русские превратности (типа суммы с разделителями любого
вида, а не только того, что жестко задан в системе, да еще зависит от текущей
языковой раскладки, как это бывает сделано у многих программеров, далеких от
реальных работников).

dbf161p2015.png

На картинке выше обрабатывается файл в формате Приложения 4 «Структура файла
передачи ОЭС» к Положению Банка России от 29 августа 2008 г. N 321-П
«О порядке представления кредитными организациями в уполномоченный орган
сведений, предусмотренных Федеральным законом «О противодействии легализации
(отмыванию) доходов, полученных преступным путем, и финансированию
терроризма». Помимо работы с таким форматом, программа также осуществляет
контроль правильности заполнения полей по требованиям этого Положения
несколькими способами.

Вы можете взять готовый бинарный файл XLSM с этой программой из Downloads
и при запуске обязательно разрешить макросы — только тогда появится меню
«Надстройки». Если боитесь запускать чужие бинарные файлы и макросы (и это
правильно!) — открывайте редактор VBA в своем Excel (может понадобится в
Настройках включить меню «Разработчик») и импортируйте туда прилагаемые
исходные тексты (здесь они все в кодировке UTF-8).

Как использовать

Раньше эта программа добавляла свою полосочку с кнопками меню, и все было
замечательно. Затем Microsoft изобрела новый Ribbon, и пользовательское меню
этой программы оказалась задвинута куда подальше — ищите в меню «Надстройки» —
как это показано на скриншоте выше. И не забудьте разрешить макросы — иначе
ничего не появится!

Меню «Надстройки»

  1. Загрузить — загрузить из файла DBF, указанного в ячейке A1, или запросить
    его имя, если там пусто (текущее содержимое будет очищено)
  2. Добавить — добавить из файла DBF, указанного в ячейке A1, или запросить
    его имя, если там пусто (текущее содержимое сохранится и будет дополнено)
  3. Просмотр — просмотр всех полей на одной форме с индикацией ошибок
  4. Печать — преобразовать выделенную строку в таблицу на отдельном листе
    для печати (одна из самых насущных функций и нравится проверяющим из ЦБ)
  5. Проверить — проверить ячейку за ячейкой по заранее составленному перечню
    правил с индикацией нарушения и возможностью исправить
  6. Сохранить — сохранить в файл DBF, указанный в ячейке A1, или запросить
    его имя, если там пусто (файл будет сформирован с той структурой, которая в
    строке 3 — описание см. ниже)
  7. Передать в Комиту — сохранить в файл DBF и передать в папку для импорта
    в Комиту (специализированный АРМ Финмониторинга)
  8. Отправить в ЦБ — сохранить в файл DBF и передать в папку для отправки
    на подпись, шифрование и далее в ПТК ПСД для отправки в ЦБ

Загрузка и сохранение

Если в ячейке A1 есть имя файла, при нажатии кнопки «Загрузить» — будет
загружен именно этот файл. Если ячейка пуста — будет диалог выбора файла.
При сохранении — аналогично. Файлы подразумеваются структуры DBF, хотя
расширение их иное!
И никогда не сохраняйте DBF через меню самого Excel — он запишет в своей
собственной структуре, подогнанной под текущие данные, но не в той, которая
регламентирована.

Работа со структурой

Одна из строк (третья на скриншоте) — структура загруженного DBF-файла,
состоящая из столбцов-полей следующего вида:

<Название поля> <Тип поля><Размер поля>

Название отделяется от типа (поддерживаются C, D, L, N) пробелом, размер
(в байтах) слитно с типом (у N может быть дробная часть после точки).
Тип и размер — или Вы знаете, о чем речь, или это есть в документации по
заполнению отчетности. Таким образом, Вы можете прочитать любой DBF-файл
(без МЕМО), создать новый или сохранить с новой структурой.

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

Полезные мелочи

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

Все прочие исходные файлы, уже никак не относящиеся к этой задаче, убраны в
папку BClient — на случай, если понадобится еще что-то из наработанного
ранее.

Также там есть папка Turniket, где находится модуль подчистки грязных
входных данных из разных источников СКУД и готовится финальная отчетная
таблица с учетом отработанного времени сотрудниками для отдела кадров.

Исходные тексты модулей

Microsoft Excel Objects

  • ЭтаКнига.cls — всего две функции: добавить меню при загрузке Workbook и
    убрать его по ее закрытию

Forms

  • UserForm1.frm — форма полноэкранного просмотра записей

Modules

  • Base36.bas — работа с 36-ричными числами, популярными в Банке России
  • Bytes.bas — работа с байтами — для CWinDos
  • ChkData.bas — правила логического контроля настраивать здесь
  • CWinDos.bas — ручная перекодировка 1251-866 с псевдографикой и фишками ЦБ
  • DBF3x.bas — ручная работа в файлами DBF версии 3, загрузка и раскраска их,
    сохранение с заданной структурой
  • Export.bas — пути экспорта
  • KeyValue.bas — вычисления ключа счета, ИНН
  • Main.bas — начальные инициализации классов, действия по завершении
  • MenuBar.bas — пункты меню
  • MiscFiles.bas — есть ли файл на диске, выбор файла и т.п.
  • MsgBoxes.bas — разные красивые диалоги
  • Printf.bas — аналог функции из языка Си
  • RuSumStr.bas — чтение суммы в любом формате, сумма прописью — для платежек
  • SheetUtils.bas — набросок макроса для сокращенной печати
  • StrFiles.bas — работа с именами файловой системы
  • StrUtils.bas — работа со строками
  • TextFile.bas — работа с текстовыми файлами

Class Modules

  • CApp.cls — класс приложения с константами и параметрами

License

Licensed under the Apache License, Version 2.0.

Перейти к содержимому

В VBA есть много интересных библиотек позволяющих работать с объектом FSO, словарями, регулярными выражениями, объектами MS Office, а также много другое.

Можно и обойтись без их подключения и использовать конструкцию CreateObject(«»), но есть два маленьких нюанса

  1. Вы теряете чуть-чуть в производительности. Я, если честно, не до конца понимаю как так, но факт есть факт. С подключенной библиотекой, на коротких примерах ускорение в 2 раза — с 0,1 сек до 0,05 сек
  2. Вы теряете подсказки в среде VBE. Для кода, который вы отдали в использование — это нормально, но для себя любимых включение может быть лишним действием (опять же вы можете в какой-то момент забыть какую библиотеку включали)

Итак, проблематика ясна. Как бороться? В три этапа.

Первый этап — макросам должен быть предоставлен доступ к объектной модели VBA. Само собой вы при этом берете на себя риски — ведь при этом макросы могут удалить все и вся.

Файл ->
Параметры ->
Центр Управления Безопасностью ->
Параметры центра управления безопасностью ->
Параметры макросов ->
Включить галочку «Предоставлять доступ к объектной модели проектов VBA»

options

Второй этап — посмотреть GUID код соответствующей библиотеки, которую будете проверять/включать программным способом. Для этого в VBE перейдите в меню и включите галочку напротив библиотеки.

Tools -> References

Ref.png

Ну и третий этап — сам макрос. Верхняя часть выводит в окно Immediate Window все библиотеки, проверяет включена ли библиотека. Ну а строчка .AddFromGuid производит подключение

Sub ref_check()

Dim i As Integer

With ThisWorkbook.VBProject.References
  For i = 1 To .Count
    Debug.Print .item(i).GUID, .item(i).Description, .item(i).Major, .item(i).Minor
    If .item(i).GUID = "{420B2830-E718-11CF-893D-00A0C9054228}" Then
      Exit Sub
    End If
  Next i
  'Microsoft scripting
  .AddFromGuid "{420B2830-E718-11CF-893D-00A0C9054228}", 1, 0
End With

End Sub


Время на прочтение
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) — тут скобки нужны постоянно.

Понравилась статья? Поделить с друзьями:
  • Библиотеки vba excel скачать
  • Библиотеки java для работы с word
  • Библиотека шаблонов для word
  • Библиотека функций в excel для чего
  • Библиотека функций excel это