Vba for excel online

This VBA tutorial will teach you the basics of using VBA with Excel. No prior coding experience? No problem! Because VBA is integrated into Excel, coding is very intuitive. Beginners can learn VBA very quickly!

The tutorial is 100% free. No sign-up is required, but by creating an account you’ll be able to save your tutorial progress, and receive many other VBA resources for free!

VBA for Excel

The tutorial contains 100 exercises spread across 10 chapters. The course is meant to replicate a «boot camp» experience where you learn very quickly by immediately completing exercises related to the course topics.

Each exericse has a «Hint» button, showing you the correct answer. So if you’re stuck, you can easily see the correct answer.

The course contents are listed below:

Although you can’t create, run, or edit VBA (Visual Basic for Applications) macros in Excel for the web, you can open and edit a workbook that contains macros. Any existing macros will remain in the workbook, and you can open the workbook in the Excel desktop app to view and edit the macros.

To edit a macro:

If you have the Excel desktop app, you can use it to work with macros. Above the ribbon, click Open in Desktop App, and follow the steps in Create, run, edit, or delete a macro.

To delete a macro:

If you open a workbook that contains macros, you won’t see any messages from Excel for the web. If you know that the workbook contains macros and you need to remove them, this must be done in the Excel desktop app. Follow the steps in Create, run, edit, or delete a macro.

Did you know?

If you don’t have a Microsoft 365 subscription, or the latest version of Excel, try it now for free:

Need more help?

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

Excel and VBA Solutions

Excel VBA Programming — Enhance your Excel skills 

Visual Basic for Applications (VBA) is a programming language used to work with Microsoft Excel, and also with other Microsoft Office applications like Word, Access, PowerPoint & Outlook, and with many third-party applications. VBA for Excel: VBA programming is used to get enhanced functionality which might be beyond an Excel spreadsheet, to automate repetitive tasks in Excel, and to integrate Excel with other Office applications such as Microsoft Access.

Excel VBA & Macros — Tutorials, Examples, Downloads & Resources 

On our site you will find tutorials, examples, downloads & resources on Excel VBA & Macros. Our Excel / VBA pages can be accessed from the Excel & VBA section, which is categorized into «Excel Tips», «Excel Functions», Excel VBA» & «Excel Pivot Tables».

Excel & VBA Services 

We provide services in respect of Excel Application which include VBA programming & development, and Financial Modeling services. Click here to know more about these services.

Excel Financial Models 

We offer Free download of some interesting Excel Financial Models: Cash Flow Waterfall Model, LBO DCF Model, Rental Property Investment Model & Property Mortgage Calculator. Click here to download.

Ebook of Excel Formulas

Excel Solutions with Advanced Formulas — An Essential Resource for Excel Users — 1000+ Formulas Across 230+ Tabs, with Explanation — Illustrated Live in Excel Workbook — Solve Real Life Problems and Resolve Complex Scenarios

This Ebook is all about providing Excel Solutions using Formulas — it illustrates using Excel Formulas to help Solve Real-Life Problems. Formulas continue to be the most important facet of Microsoft Excel, and using Excel without formulas would be rare. Towards this we have attempted to cover a wide range of aspects and functions, with a Live illustration in this Excel Workbook of providing Solutions using Excel Formulas. 

The aim is for you to master Excel Formulas for all situations, while keeping them easy! Click here to know more about the Ebook of Excel Formulas

Excel VBA Online Tutorial

Learn Excel VBA programming with our easy to understand Excel VBA Online Tutorial — access examples & illustrations, live codes and downloadable files which will make learning VBA simple and quick for you. If you are finding VBA difficult to learn, or if you find it too complicated, or if you feel it is beyond your capacity, then you have come to the RIGHT place. We keep it easy! Our tutorial is in plain language, in English, and will enable you to master Excel VBA effortlessly. Check out what some existing users have to say about our Excel VBA Tutorial (click for all Testimonials):

«Thanks very much. Excellent tutorial … Looked like a nightmare on other sites. This one broke it down and showed it best. Cheers!»

«I find your site very informative and written in understandable language.»

«Thank you for sharing your excellent, clear VBA explanations. It saves my time.»

«I have been teaching myself VBA over the past 5 months by incorporating it into many useful projects. I have purchased several well-known books and searched the internet extensively as I’ve encountered problems. I don’t know what took me so long to come across your site, but it is without a doubt, the best site on the web for getting a good handle on VBA. The clear examples and descriptive notes are very informative. You provide much depth while keeping it simple.»

«Good Work! One of the best sites i have come across.!! I was stuck up in a problem fr 3 days….n i got it solved here..!! Many Many thanks :)»

«I was completely taken back by the amount of information and examples that were offered. I stopped writing my code, and I spent over two hours exploring the MANY facets of this site. The whole time, I was saying, » Wow!…. Wow!… Wow!» . Your explanations and examples have helped me a great deal!»

«I’ve been to all kinds of excel schools, addin, books, excel program like … Finding ways to make me understanding excel in shortcut mode. Wanted to know the code and just copy with simple reason about the code. Done. period. I’m thankful for your work … and give me more information if there’s more.»

Brief Contents: Excel VBA Basics; VBA Objects; Working with Variables; Conditional Statements; VBA Loops; Application Object; Workbooks & Worksheets; Cells & Ranges in VBA; String & Date Functions; VBA Procedures & Functions; VBA Arrays; Error Handling; Events; Custom Classes & Objects; UserForms; Charts, Shapes, ActiveX & Form Controls; PivotTables with VBA; Automation with VBA (Send Email from Excel, Automate PowerPoint, …); Connect with Databases — ADO, ADOX &  DAO;

Methodology: You can create a Free Login Account and then Login with your username and password to access our Online Tutorial. You will get complete access to the Excel VBA course, structured in appropriate Sections, with Live Codes & Downloadable Excel Files. You can learn VBA from the comfort of your house or office, 24 x 7, without any time limits, explained in a simple and easy manner. Click here to know more about the Excel VBA Online Tutorial.

Come join us, in the marvelous world of VBA programming, to discover the magic of VBA!

We hope you enjoy navigating our site, and find it useful. We welcome your feedback and will earnestly consider all your valuable inputs.


March 28, 2020/



Chris Newman

Enable Office Scripts Excel Online

Excel for the web (aka Excel Online) now has scripting functionality akin to VBA! We are in the early stages of this new scripting language, however, if you would like to get a head start in learning this new language to automate tasks on Microsoft’s online Apps (this does not work for Desktop apps…for now), you may be able to convince your Admin to turn on this new feature. The code editor and script recorder are located on the Automate tab in Excel which is hidden by default. The following brief tutorial will show admins how to enable this feature.

Script Editor.png

Further Script Documentation

Who Can Use This?

This feature is in preview and only available to users in E3 Tenants and E5 Tenants that have had their admin enable Scripts for Excel Online.

Accessing the Admin Center

To access the Admin Center on Office 365 you will need to log into Office.com and select the Admin App on your dashboard. If you do not see the Admin App, you can click the right arrow icon to view all your apps. In the event you cannot find the Admin App after viewing all your apps, chances are you do not have Admin rights.

Open Admin Center.png

Open Admin Settings

Once you’ve clicked the Admin App, you should be taken to a new webpage with a pane menu on the left-hand side. You will need to select Settings > Settings. If you do not see an Settings menu option, you may need to click the Show All option at the very bottom of the listing.

Select Settings.png

Open Office Scripts Settings

After you have navigated to the Settings section, ensure you are in the Services part of the settings and click the Office Scripts option.

Office Scripts Settings.png

Enable Office Scripts

After opening the Office Scripts Settings, you should see a pane to the right of your screen. You should see a checkbox option similar to below that will allow you to enable Office Scripts.

Enable Office Scripts.png

Access Office Scripts

After Office Scripts have been enabled by your Office Admin, you can refresh Excel Online (you may need to close out of it completely) and after reopening, you should see a new tab in your Ribbon called Automate. There will most likely be more button residing in this tab in the future, but for now you have access to a Script Recorder (online version of the Macro Recorder) and a Code Editor pane.

For more information on what all Scripts can do, check out the Microsoft documentation.

Excel Online Automate Tab.png

I Hope This Helped!

Hopefully, I was able to explain how you can enable this new feature for Excel Online. While scripting is still a work in process, there is a lot of automation you can carryout within Excel and in combination with Power Automations to automate your cloud activity. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

Chris Newman 2020.jpg

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you some value today and hope to see you back here soon! — Chris

Понравилась статья? Поделить с друзьями:
  • Vba for excel instr
  • Vba import word to excel
  • Vba for excel insert row
  • Vba hyperlink excel cell
  • Vba for excel inputbox