Visual basic запуск excel

Как в Excel 2010 или 2013 вставить и запустить код VBA – руководство для начинающих

​Смотрите также​ _ «C:UsersCDesktopFOLDER» Workbooks.Open​IvanOK​Юрий М​Хоть Жераром Депардье​ все твои сообщения​ этом. Как только​ файл с несовпадающим​зы. кстати, везде,​’ Returns collection​ Ned_Poriv() exl =​а это читали:​

​ по его использованию​Окно​(Sheet);​ Basic, как показано​Application.ScreenUpdating = False​Это краткое пошаговое руководство​ Filename:= _ «C:UsersÍDesktopFOLDERFILENew.xls»​:​: Кирилл, а рекордер​ или психом в​ выискивая в них​ Михаилу потребуется изменить​ именем — нужный​ где возможно, я​ files of folder​

​ CreateObject(«excel.application») exl.Workbooks.Open(Filename:=»C:Documents and​’111 это пароль​ (в приложении) :​Watches​Код более общего характера​ на картинке ниже.​Application.Calculation = xlCalculationManual​ предназначено для начинающих​ on error goto​IvanOK​ упорно пишет ChDir​ белой рубашке с​ «перлы» а ля​ что-то в коде,​

  • ​повторюсь: моя функция​ тоже предпочитаю однострочный​
  • ​’​ SettingsСемРабочий столExcel.xls») exl.Sheets(«Період2»).Select()​

Вставляем код VBA в книгу Excel

​ на открытие файла,​[ссылка заблокирована по​также очень помогает​ должен быть введён​ Имейте ввиду, что​В самый конец кода,​

    1. ​ пользователей и рассказывает​ 0 дальше код​
    2. ​, На горе программист:​​ ))​​ пеной у рта​ nerv? Хочешь быть​Вставляем и запускаем макрос в Excel
    3. ​ ему придется ковырять​​ абстрагируется от (свой,​​ If.​’ @param {String}​ exl.visible = True​ 11 это пароль​ решению администрации проекта]​ при отладке кода​ в​​ окно Excel остается​​ перед​​ о том, как​​ работы с открытым​Вставляем и запускаем макрос в Excel
    4. ​ThisWorkbook.Windows.Application.Visible = False​KL​ (в ваших глазах).​ нарциссом — ради​ всю логику, в​ чужой и т.п.).​​Vitalts​​ Path The path​Вставляем и запускаем макрос в Excel​ exl.Sheets(«71010000»).Select() exl.Cells.Select() exl.Selection.Delete(Shift:=xlUp)​​ на изменеие​S_e_m​

      ​ VBA, так как​Module​ открытым и находится​

      ​End Sub​
      ​ вставлять код VBA​

      ​ файломно очевидно, что,​ UserForm1.Show​: Юр, ну мало​ Моя точка зрения​ Бога. Растеряешь друзей.​ т.ч. логику получения​

      • ​ Она просто возвращает​:​ to folder​​ exl.Sheets(«Період1»).Select() exl.Cells.Select() exl.Selection.Copy()​​Вы что тоже​: Ребята, подскажите как​​ в нём можно​​;​ позади окна редактора.​​:​​ (Visual Basic for​

        ​ если ошибки при​
        ​eagl69​

      • ​ ли что на​ останется при мне​​RAN​​ имени файла из​

        ​ список файлов папки.​
        ​Michael_S​

      ​’ @param {String}​ exl.Sheets(«71010000»).Select() exl.Cells.Select() exl.ActiveSheet.Paste()​ создали файл с​ открывается книга Excel​ увидеть значение, тип​Код для нового объекта​В процессе работы в​Application.ScreenUpdating = True​ Applications) в книгу​ обращении по 1​:​ заборах пишут. Рекордер​Цитата​: Саш, это, конечно​ папки. В моем​ При желании может​, что значит не​ [Filter] The file​

    5. ​ exl.Rows(«1:1»).Select() exl.Range(Selection, Selection.End(xlDown)).Select()​ такими паролями?? плагиат​ 2003 c указанного​ и контекст любого​​ должен быть введён​​ редакторе Visual Basic​Application.Calculation = xlCalculationAutomatic​​ Excel, и как​ пути нет, то​inv.DS​​ еще и Select​(RAN)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Ты откатись чуть​ правильно​ случае это не​​ делать это рекурсивно.​​ хочет? Без кода​Вставляем и запускаем макрос в Excel​ filter​​ exl.Application.CutCopyMode = False​​ какой-то, деньги автору​ места.​​ отслеживаемого выражения, которое​​ в​ в Excel могут​​Эти строки, как можно​ запускать вставленный макрос​​ как избежать обращения​,​​ обожает​​ назад, и взгляни​

Вставляем и запускаем макрос в Excel

  1. ​но вся проблема​​ требуется, т.к. вынесено​​Функцию можно подключить​ я не могу​’ @return {Collection}​ exl.Selection.Sort(Key1:=Range(«E1»), Order1:=xlAscending, Header:=xlGuess,​

Запускаем макрос VBA в Excel

​ пароля??? ))​Наперед СПАСИБО!!!​​ задаст пользователь. Чтобы​​Class Module​​ быть открыты различные​​ понять из их​​ для выполнения различных​​ ко второму пути?​inv.DS​Юрий М​​ на свои коды.​​ в том -​

Вставляем и запускаем макрос в Excel

​ в функцию. Если​ и не вносить​
​ сказать где у​
​ FileList​

​ _ OrderCustom:=1, MatchCase:=False,​

office-guru.ru

Редактор Visual Basic в Excel

​S_e_m​Ципихович Эндрю​ открыть окно​;​ окна. Управление окнами​ содержания, отключают обновление​ задач на этом​спасибо за советы.​, неа ефекто тот​: ))​И переменные из​ что она одна,​

Запуск редактора Visual Basic

​ ему потребуется проверять​ существенных изменений в​ вас ошибка, ибо​’ —————————————-​​ Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal)​​: Так открывается с​: в ВБА так:​​Watches​​Если нужно создать диалоговое​ осуществляется в меню​​ экрана и пересчёт​​ листе.​МатросНаЗебре​ же….​Assassinys​ одной буквы, и​ но для всех​ вложенные каталоги, ему​ основную программу (добавляется​

Редактор Visual Basic в Excel

Окна редактора Visual Basic

​ код замечательно работает.​Private Function GetFileList(ByVal​ ‘oExcel.Workbooks.Add() ‘oExcel.Sheets.Add.Name =​ этими паролями и​Set oExcel =​, нажмите​ окно для взаимодействия​ View, которое находится​ формул рабочей книги​Большинство пользователей не являются​:​

Окно проекта (Project)

​нужно сделать до​​: Собственно меня интересует​​ Iif сплошь и​ разная!​ придется писать новый​ одна строка вызова​ Ни один год​ Path As String,​ ComboBox1.Text End Sub​ без них. Загвоздка​ CreateObject(«Excel.Application») ‘создать объект​Watch Window​ с пользователем, то​ в верхней части​ перед выполнением макроса.​ гуру Microsoft Office.​

  • ​If Err <> 0​​ sub workbook_open() иначе​​ как возможно открыть​ рядом, и еще​
  • ​Ты откатись чуть​​ алгоритм (перебирать всю​​ функции).​ пользуюсь подобными методами.​ _​Редактор Visual Basic в Excel

​ End ModuleПосле запуска​ в том, что​​ Microsoft Excel oExcel.Workbooks.Open​​в меню​​ можно использовать​​ окна редактора VBA.​​ После выполнения кода​​ Они могут не​ Then​ ефект полюбому останется….​ форму в документе​ куча всего, что​​ назад, и взгляни​​ логику, вносить изменения,​​Цитата​​Попробуйте вывести название​​Optional ByVal Filter​​ в конце строки​

​ я дальше хочу​ «D:Рабочая папка» &​​View​​Userform​​ Ниже дано описание​​ эти параметры снова​​ знать всех тонкостей​​all L​

  • ​ потому что сначала​​ эксель но так​​ ты сейчас критикуешь!​ на свои коды.​ отлаживать и т.п.​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Я уж не​ файла, который пытаетесь​
  • ​ As String =​​ 27 выдаёт ошибку​​ выделить какой-то диапазон​ Имя_файла, , ,​​редактора Visual Basic.​​.​​ отдельных окон.​​ включаются. Данный приём​​ работы той или​​: Попробуем. спасибо!​

​ открываеться ексель а​ что бы была​в том то​И переменные из​ всю программу, а​ говорю о размере​ открыть, возможно, лимит​

  • ​ «*») As Collection​ —-​ ячеек и копировать​ , «111», «11»​​ Также окно​​Двойной щелчок мышью по​
  • ​Окно​ приводит к ускорению​ иной функции, и​Sanja​​ потом он выполняет​​ видна только форма​
  • ​ и дело. Я​ одной буквы, и​ не отдельную функцию).​​ кода.​​ исчерпан, и идет​
  • ​Static List As​Object variable or With​ их, а мне​​ ‘111 это пароль​​Watches​
  • ​ любому объекту в​Project​ выполнения макроса от​ не смогут ответить​​: :?:​​ макрос​

Окно кода (Code)

​ при открытии документа​ сам делал так​ Iif сплошь и​​Если вы предпочитаете​​Качество кода не​​ попытка открыть файл​​ New Collection​ block variable not​ выдает ошибку на:​ на открытие файла,​будет открыто автоматически,​ окне​​открывается в левой​​ 10% до 500%​

​ на вопрос, как​If Err <>​​IvanOK​​ а сам документ​ (писал ужасный, говеный​ рядом, и еще​ закладывать фундамент дома​ измеряется его размером.​ с пустым названием.​

Окно свойств (Properties)

​Static FSO As​​ set.​​Range​ 11 это пароль​ если задать отслеживаемое​Project​ части редактора VBA​ (да, макрос может​ отличается скорость выполнения​ 0 Then PathName​, Вы бредите! Все​ был скрыт или​ код) и не​

Редактор Visual Basic в Excel

Окно отладчика (Immediate)

​ куча всего, что​​ из спичек, я​​ Вообще, не понимаю,​ Не совершенство кода,​ Object​​—​​(«A8:C7»).Select Ощущение, что​​ на изменеие ‘oExcel.Workbooks.Open​​ выражение.​открывает соответствующее окно​​ (показано на картинке​​ работать в 5​ макроса VBA в​ = ChDir(«Y:PublicFolder1») Else​ работает у меня​ свернут?​ хочу, чтобы кто-нибудь​ ты сейчас критикуешь!​ не против, но​ почему форумчан беспокоит​

​ написанного на скорую​​Static Deep As​​Также в 29​​ книга «AIC_SIP» активна​​ «D:Рабочая папка» &​Чтобы задать отслеживаемое выражение,​Code​​ выше). В этом​​ раз быстрее, если​

Редактор Visual Basic в Excel

Окно переменных (Locals)

​ Excel 2010 и​​ PathName = ChDir(«C:UsersCDesktopFOLDER»)​​ остается только 1​​аналитика​​ еще наступал на​​Мне Вася уронил​​ сам стараюсь этого​ размер (не только​ руку :(​ Integer​ строке​ (потому что окрыта),​ Имя_файла, , ,​ нужно:​, предназначенное для ввода​ окне для каждой​ манипуляции над ячейками​ 2013. Многие просто​​ End If Workbooks.Open​​ форма активная, сам​: в модуль «ЭтаКнига»:​

Редактор Visual Basic в Excel

Окно отслеживания (Watches)

​ эти грабли. Это​​ молоток на голову!​​ не делать​ этого) кода, если​Судя по скрину,​Dim SubFolder As​Range​ а Лист1 не​ ,111, 11 ‘111​Выделить выражение в редактируемом​ кода VBA с​​ открытой рабочей книги​​ происходят без лишних​​ используют Excel, как​​ Filename:=PathName & «FILENew.xls»​​ Excel прячется.​​sub workbook_open() application.visible=false​ ж очевидно )​​И что вы​​Цитата​ код написан должным​ так и есть.​

Редактор Visual Basic в Excel

​ Object​Ошибка 1 «System.Data.Range»​

  1. ​ активный и не​ это пароль на​
  2. ​ коде VBA.​​ клавиатуры. На одном​​ создаётся проект VBA​​ остановок).​​ инструмент для обработки​
  3. ​Kuzmich​​inv.DS​​ yourform.show end sub​

​deathogre​ ему сказали?​(Serge_007)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Кстати и скорость​ образом? Подключили, забыли.​ Приведите код​Dim Folder As​ в этом контексте​ хочет с ним​

​ открытие файла, 11​В меню​
​ из приведённых выше​
​ (VBA Project). Проект​

​Сохраняем рабочую книгу, как​

office-guru.ru

Как открыть visual basic через excel в office 2007?

​ данных.​​: Используйте диалоговое окно​

​, ето вы просто​​Assassinys​
​: Здрасьте. Как программно​Ты…, Вася…, неправ!!!!!!!!!​ тоже от длинны​

​ Если хотите по​​Michael_S​ Object​
​ недоступен, так как​ контачить.​
​ это пароль на​Debug​ рисунков показано окно​
​ VBA – это​ книгу Excel с​Предположим, нужно изменить данные​ выбора файла​
​ не замечаете не​: не работает(​ открыть книгу эксель​nerv​
​ не всегда зависит​ прежнему заниматься ручной​: Vitalts, Все, разобрался.​

​Dim File As​​ является «Friend».​Спасибо что отозвались​ изменеие oExcel.Visible =​редактора VBA нажать​

Как в excel открыть visual basic???

​ кода для​​ набор всех объектов​ поддержкой макросов. Для​ на листе Excel​
​Set FD = Application.FileDialog(msoFileDialogFilePicker)​ мощном ПК, а​

​Assassinys​​ и сохранить эту​: об единственной опечатке​зависит от алгоритма,​ обсфукацией, экономить на​ Не туда​ Object​dzug​ (ещё раз)​ True ‘FalseНеужели в​Quick Watch​Module1​ и модулей VBA,​ этого нажмите​
​ определённым образом. Мы​all L​ я говорю делоВ​

​:​​ книгу (объект) в​ я предупредил сразу.​ а не от​
​ каждой букве, пожалуйста.​Set wb = Workbooks.Open(ActiveWorkbook.Path​

Открытие Excel и активация нужного листа

​If FSO Is​​: Посмотрите это:​Ципихович Эндрю​ ВБ не так??​.​
​.​

​ привязанных к текущей​​Ctrl+S​
​ немало погуглили и​: Kuzmich, Sanja, спасибо​ продолжение темы:​Assassinys​ глобальной переменной?​ Это раз. Два,​ кол-ва букв )​Я пишу универсальные​ & «» &​ Nothing Then​Обработка активной книги​: Это решено???????? и​ проверьте, отпишитесь, ОК??​Нажать​По мере ввода кода​ книге. Изначально в​и в окне​ нашли макрос VBA,​ за советы. Начну​Private Sub CommandButton8_Click()​

​, работает.​​Юрий М​ кто-то не знает,​Цитата​ функции, кот. таскаю​ fn)​Set FSO =​ Excel​ ладно …​S_e_m​Add​ VBA в окно​ него входят:​ с предупреждением​ который решает эту​ с предложения Sanja​ Application.Visible = False​Код надо поместить​
​: 1. Открытие нужной​ что от него​(Serge_007)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Мы все тут​
​ (использую) из проекта​впихивал.​ CreateObject(«Scripting.FileSystemObject»)​S_e_m​здесь​: Всё так. Только​.​Code​Объект​Следующие компоненты невозможно сохранить​ задачу. Однако, наше​ (для сохранения «молчаливой»​ End Sub Private​ куда и сказано​ книги запишите макрорекордером​ хочет компилятор при​ хотим размер покороче​ в проект. Мне​Еще раз спасибо.​End If​: Ничего не помогает.​Windows(«AIC_SIP.xls»).Activate ‘активация моего​ я, пока, чайник​Кроме рассмотренных, в меню​, редактор Visual Basic​ЭтаКнига​ в книге без​ знание VBA оставляет​ работы процедуры), если​ Sub CommandButton9_Click() Application.Visible​ -​ — получите готовый​

​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Option Expicit​​ и даже соревнуемся​ это не мешает​nerv​If FSO.FolderExists(Path) Then​ Не получается у​ файла Range(«A1:C3»).Select ‘выбираю​ и совсем недавно​ редактора Visual Basic​ следит за правильностью​(ThisWorkbook), привязанный к​
​ поддержки макросов​ желать лучшего. Вот​

​ не подойдет, то​​ = True End​
​в модуль «Эта книга»​ код.​
​я тут не​
​ в этом постоянно​
​ ) Если вам​: просто вы не​Set Folder =​ меня сортировка. Уже​
​ диапазон ячеек Selection.Copy​ начал изучать язык​ в Excel существует​ ввода, ищет ошибки​ книге Excel;​

​(The following features​​ тут-то и придёт​ окно выбора файла​ SubЛист скрывается а​yourform​2. Dim Wb​ при чем )​ в специально созданном​ нравиться каждый раз​ писали МНОГО кода​​ FSO.GetFolder(Path)​​ кучу сайтов перелазил​ ‘копируюв переди пробуйте​ программирования, а тут​ ещё множество параметров​ в коде и​Объекты​ cannot be saved​
​ на помощь пошаговая​ уж точно поможет.​

​ вот при открытии​​заменить на свое,​ As Workbook Set​
​Цитата​
​ для этого разделе​ переписывать весь код,​Когда перед тобой​For Each File​ — не могу​
​ добавлять oExcel.​ ещё по работе​
​ и команд, используемых​ выделяет код, который​

​Лист​​ in macro-free workbook)​ инструкция, с помощью​
​ вопрос, думаю, закрыт.​ появляется еще какой​
​ например, у меня​ Wb = ActiveWorkbook​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Ты упорно пытаешься​за рекламу 5​ я не против​ 1000+ строк в​ In Folder.Files​ разобраться.​то есть как​ нужно было… Короче​ при создании, выполнении​ требует исправления.​(Sheet), привязанные к​ нажмите​ которой мы сможем​ Спасибо.​ то лист пустой​Userform1​Hugo​
​ доказать всем участникам​Michael_S​Serge_007​ одном только модуле,​If File.Name Like​Michael_S​ Вы здесь обращались:​
​ получилось, но открывает​
​ и отладке кода​В окне​ каждому листу текущей​Нет​ использовать найденный код.​

​Александр Моторин​​all L​Aleksey1404​: Set wb =​ темы​

​: У каждого свои​​: Точно так же​ нет желания разбирать​ Filter Then​: Все, что об​oExcel.Visible = True​ не из всех​
​ VBA.​Properties​ рабочей книги Excel.​(No).​Вставляем код VBA в​: А где находится​: Добрый день,​: Да заработало ,​ Workbooks.Open(filename)​я отстаиваю свою​ понятия «правильности»​ как и формул.​ и додумывать. Хочется​List.Add File​ этом файле известно​ ‘False​ папок. С некоторых​Урок подготовлен для Вас​перечислены свойства объекта,​Самостоятельно в проект можно​Откроется диалоговое окно​ книгу Excel​ сам файл?​Подскажите, можно ли​ я просто имя​deathogre​ точку зрения​Саш, мы уже​ Кстати и скорость​​ просто читать. Максимально​End If​ — он находится​​S_e_m​
​ папок выдаёт ошибку,​ командой сайта office-guru.ru​​ который в момент​​ добавить объекты​Сохранение документа​Запускаем макрос VBA в​Если рядом с​

​ решить такую задачу:​​ формы некорректное выбирал​
​: Мне нужно открыть​Цитата​

​ как-то говорили на​​ тоже от длинны​ быстро читать понятный​Next​ в той же​: Я уже на​ что нету доступа.​

CyberForum.ru

Открыть файл excel. (VBA) (Задача вроде простая, но…)

​Источник: http://www.excelfunctions.net/Visual-Basic-Editor.html​​ создания (не в​Userform​(Save as). В​ Excel​ нужным файлом, то​Работаю с файлом,​Апострофф​ книгу из другой​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>и правда думаешь,​ эту тему; твои​ не всегда зависит​ не двусмысленный код.​For Each SubFolder​ папке, где и​
​ пике восторга​ Если знаете в​

​Перевел: Антон Андронов​​ процессе выполнения программы)​,​

​ выпадающем списке​​В этом примере мы​ ActiveWorkbook.Path поможет​ в котором прописана​: А как обратно​
​ книги​
​ что кому-то интересно​ доводы отчасти верны,​
​Однако ты прав,​
​ "С недавних пор"​ In Folder.SubFolders​
​ основной, и других​Получилось, как Вы​
​ чем проблема, отпишите​Автор: Антон Андронов​
​ выделен в окне​
​Module​
​Тип файла​
​ будем использовать VBA​

​all L​ VBA-процедура, на работе​ открыть файл для​Юрий М​
​ искать все твои​ но не для​ форумчан это очень​
​ однострочный If я​
​Deep = Deep​ файлов в этой​ сказали. Вот так​ пожалуйста. А пока,​

​Виталик александровский​​ проекта. Эти свойства​и​(Save as type)​
​ макрос, который удаляет​: Нет, Александр, не​ и дома.​
​ редактирования (((​
​: И что?​ сообщения выискивая в​
​ всех случаев.​
​ беспокоит​
​ не использую вообще​ + 1​
​ папке нет. И​
​Set oExcel =​ очень благодарен за​: Alt плюс F11​
​ могут быть различными​Class Module​ выбираем​
​ переносы строк из​ с нужным. Спасибо.​
​Процедура эта в​
​Aleksey1404​deathogre​ них "перлы" а​
​Michael_S​Мы все тут​ )​
​GetFileList SubFolder.Path, Mask​ что он -​
​ CreateObject("Excel.Application") 'создать объект​ помощь!!!​
​Gkp090​ в зависимости от​
​. Если Вы посмотрите​Книга Excel с поддержкой​
​ ячеек текущего листа​RAN​
​ процессе работы обращается​: Разве не очевидно?​
​: Объявил глобальную переменную​ ля nerv?​
​: То же не​ хотим размер покороче​
​Цитата​
​Next​
​ эксель. Ни имя​ Microsoft Excel oExcel.Workbooks.Open​
​В принципе разобрался​: VBA​
​ типа выделенного объекта​ на картинку выше,​
​ макросов​
​ Excel.​
​: Не тестировал, но​
​ к еще одному​ Application.Visible = True​
​ в модуле ЭтаКнига​если мне говорят,​
​ работает​
​ и даже соревнуемся​
​(Michael_S)200?'200px':''+(this.scrollHeight+5)+'px');">жалуется на Mask​Deep = Deep​
​ и расширение файла,​
​ "C:Documents and SettingsS_e_mРабочий​ с открытием, но​
​в настройках выставить​ (лист, книга, модуль​
​ то увидите, что​(Excel macro-enabled workbook)​
​Открываем рабочую книгу в​ на правду похоже​
​ файлу (открывает его,​
​Апострофф​
​ Public Главнейшая As​

​ что я не​nerv​smile​ в этом постоянно​Это та самая​

​ — 1​​ а также имя​​ столAC_SIP222″ & xls​​ тут проблема дальше​ «Показывать вкладку Разработчик​ и другие).​smile​ в проект VBA​ и нажимаем кнопку​
​ Excel.​Sub Мяу() Dim​ производит определенные действия),​: Может есть какое-то​ Workbookоткрыл книгу в​ прав, я спрашиваю​: Захотелось кнопку «Ok»​ в специально созданном​
​ ошибка, о кот.​End If​ и расположение папки​ ‘открываю книгу 222​

​Private Sub Command1_Click()​​ на ленте»​Окно​ для книги​
​Сохранить​Нажатием​ wb As Workbook​​ который на работе​​ сочетание клавиш, позволяющее​ модуле АктивХ формы​ в чем, а​ нажать​ для этого разделе​
​ я говорил. Замените​
​If Deep =​ не известны.​ oExcel.Visible = True​ Set oExcel =​

​Александр к​​Immediate​​Book1.xlsm​​(Save).​Alt+F11​ Dim pName(), fName$,​ лежит на диске​ открыть файл без​ChDir «\Margo123Тест» Workbooks.Open​ не заведомо соглашаюсь​Там же написано​
​KuklP​ Mask на Filter.​ -1 Then​Возможно? Если возможно​ ‘False oExcel.Range(«B5:E13»).Select ‘выбираю​ CreateObject(«Excel.Application») ‘ñîçäГ*ГІГј îáúåêò​: На вкладке Разработчик​можно отобразить в​добавлен объект​
​Нажимаем​вызываем окно редактора​ i& pName =​

​ Y, дома на​​ отработки макроса(shift не​ Filename:=»\Margo123Тест6.02.2016.xlsm» Set ЭтаКнига.Главнейшая​​Цитата​ «Переменная не определена»​: Еще как измеряется.​​Цитата​
​Set GetFileList =​

​ — как?​​ диапазон ячеек oExcel.Selection.Copy​ Microsoft Excel oExcel.Workbooks.Open​smile​ щелкните Visual Basic.​ редакторе Visual Basic​Module​Alt+Q​ Visual Basic​ Array(«Y:PublicFolder1», «C:UsersCDesktopFOLDER» fName​ диске С. Имя​ помогает), т.к. у​ = Workbooks(«\Margo123Тест6.02.2016.xlsm»)выдает ошибку​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Растеряешь друзей.​ и даже выделено​ Можно написать на​
​(Vitalts)200?’200px’:»+(this.scrollHeight+5)+’px’);»>В данном случае,​​ List​
​nerv​ ‘копирую oExcel.Workbooks.Open «C:Documents​ «C:111AIC_SIP» & AIC_SIP,​Если Вкладка Разработчик​
​ через меню​​с названием​, чтобы закрыть окно​На панели​ = «хи-хи.xls» On​ файла одинаковое, пути​ меня отображается форма,​
​ на 3 строке,​т.е. если наши​ какая. Что мешает​
​ 10 страниц «правильного»​​ мне караз таки​Set List =​: Получить список файлов​ and SettingsS_e_mРабочий столAC_SIP111″​
​ , , ,​ не отображена:​View​Module1​ редактора VBA и​Project-VBAProject​ Error Resume Next​ к нему разные.​ но я не​

​ Run-time error 9​​ мнения не совпадают,​ объявить? Это же​ кода, а можно​
​ было удобнее воспользоваться​ Nothing​ папки​ & xls ‘открываю​ 111, 11 ‘111​Нажмите кнопку Microsoft​>​.​ вернуться к книге​кликаем правой кнопкой​

​ Do While wb​​Сейчас обращение к​ могу добавить код​ Subscript out of​smile​ то я уже​ пример )​ то же действие​
​ однострочным if, дабы​​Set FSO =​Vitalts​ другую книгу 111​
​ ГЅГІГ® ГЇГ*ðîëü Г*Г*​ Office, а затем​Immediate Window​Вот как можно создать​ Excel.​ мыши по имени​ = Nothing Set​
​ этому файлу выглядит​ по причине отсутствия​ range​ автоматически не друг,​Цитата​ описать одной строкой.​
​ не закрывать, а​​ Nothing​: Все названия Excel​ oExcel.Visible = True​
​ îòêðûòèå ГґГ*éëГ*, 11​ — Параметры Excel.​или нажатием комбинации​ новый объект​Чтобы запустить только что​ рабочей книги (в​ wb = Workbooks.Open(Filename:=pName(i)​ следующим образом:​ окна екселя… код​Юрий М​ потому, что «мнения​(Michael_S)200?’200px’:»+(this.scrollHeight+5)+’px’);»>У каждого свои​
​ Что легче можно​ перенос для наглядности.​Deep = 0​ файлов в папке​ ‘False oExcel.Range(«A1»).Select ‘Выделил​ ГЅГІГ® ГЇГ*ðîëü Г*Г*​Щелкните Популярное и​ клавиш​Userform​smile

​ добавленный макрос, нажмите​​ левой верхней части​ & fName) i​1ый путь:​ не большой написан,​: Глобальную переменную в​
​ друзей должны совпадать​ понятия «правильности»​ будет понять и​
​для наглядности многострочный​End If​ активной книги, исключая​ стартовую ячейку oExcel.ActiveSheet.Paste​ èçìåГ*ГҐГЁГҐ oExcel.Visible =​ затем установите флажок​biggrin

​Ctrl+G​​,​Alt+F8​ окна редактора) и​ = i +​Sub MyCode ()​ просто стало интересно)​ стандартный модуль -​ всегда»? (это следует​вообще-то нет​ отредактировать? Ведро картошки​ If. В вашем​End Function​ ее:​ ‘ВставилЭто для примера,​​ True ‘False Windows(«AIC_SIP.xls»).Activate​​ Показывать вкладку «Разработчик»​. Это окно помогает​biggrin

​Module​​. Откроется диалоговое окно​ в контекстном меню​smile
​ 1 Loop End​​ ChDir _ «C:UsersCDesktopFOLDER»​Aleksey1404​ будет доступна всюду.​ из твоих слов)​Правильность она «одна​
​ можно отвезти на​ случае это неочевидность.​впрочем, уже вижу​
​200?’200px’:»+(this.scrollHeight+5)+’px’);»>​​ может комуто и​ ‘Г*ГЄГІГЁГўГ*öèÿ ìîåãî ГґГ*éëГ*​ на ленте.​
​ при отладке кода.​или​Макрос​ выбираем​ Sub​
​ Workbooks.Open Filename:= _​​:​ И модуль не​Цитата​ на всех мы​
​ мопеде, не нужен​Цитата​ косяк​Dim fn As​ понадобится.​ Range(«A1:C3»).Select ‘âûáèðГ*Гѕ äèГ*ГЇГ*çîГ*​Примечание. Лента является​ Оно выполняет роль​Class Module​(Macro). В списке​Insert​Doober​ «C:UsersÍDesktopFOLDERFILENew.xls» дальше код​Aleksey1404​ нужно указывать.​(RAN)200?’200px’:»+(this.scrollHeight+5)+’px’);»>но вся проблема​ за ценой не​ для этого БелАз.​(Vitalts)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Кстати, проверки названий​но не критичный​ String​Но всегда есть​ ГїГ·ГҐГҐГЄ Selection.Copy ‘êîïèðóþ​
​ частью интерфейса «Пользовательский​ области вывода для​:​Имя макроса​>​: Проверил,работает​smile
​ работы с открытым​​, Вы наверно не​Если книга уже​ в том -​
​ постоим», только это​ Но если тебе​ файлов на самого​
​ )​​With ActiveWorkbook​ но… Дальше у​ End SubВыдаёт ошибку​ интерфейс Microsoft Office​ отладки выражений и​В окне​
​(Macro name) выберите​smile

​Module​​Sub Гав_Гав() PathForFile$​ файломДальше работа с​
​ с того конца​ открыта — зачем​ что она одна,​ не все понимают​ так​ себя у вас​

​Vitalts​​fn = Dir(.Path​ меня куча строк​sad

​ и что хочешь​​ Fluent».​ позволяет вычислять отдельные​smile​Project​ нужный макрос и​.​ = Get_Folder &​ открытым файлом.​ начали программу писать​
​ указывать путь?​​ но для всех​ )​
​нравитЬся​smile​ нет.​:​ & «*.xls*»)​ с заданием (макрос​ делай. Подскажите пожалуйста​В меню Справка​
​ выражения или выполнять​​выберите рабочую книгу,​ нажмите кнопку​Копируем код VBA (с​ «FILENew.xls» End Sub​И когда мне​Сначала следовало забить​
​deathogre​ разная!​Цитата​

​, я тоже не​​функция, представленная мной​nerv​Do Until fn​ короче написан). Мне​ как активизировать тот​ выберите пункт Справка:​ строки кода по​ в которую нужно​Выполнить​
​ веб-страницы или из​ Public Function Get_Folder()​ надо поменять путь​ в форму код,​: Мне нужно в​Не поверишь, есть​​(Michael_S)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Саш, мы уже​​ против​ возвращает список файлов​, эээ, и вы​ = «»​ что, перед каждой​ лист и работать​ Microsoft Visual Basic.​ одной.​ добавить объект, и​(Run).​ другого источника) и​

​ As String Set​​ к этому файлу,​а потом в​
​ открытую книгу писать​ нюансы, но в​ как-то говорили на​nerv​ заданной папки. Понятия​
​ утверждаете что у​If fn <>​ командой ставить oExcel?​
​ в нём (я​Роман царьков​Например, введите выражение «​ кликните по ней​Урок подготовлен для Вас​ вставляем его в​
​ FSO = CreateObject(«Scripting.FileSystemObject»)​ я его просто​
​ прятки с​ изменения, через глобальную​
​ целом правильность одинаковая​

​ эту тему; твои​​: чуть меньше неверно,​ «самого себя» здесь​ меня извороты?​ .Name Then: _​Всё!!! Получилось. Строка​ так понимаю, нужно​
​: кнопка Visual Basic​
​?j​ правой кнопкой мыши.​
​ командой сайта office-guru.ru​​ правую область редактора​ If FSO.FolderExists(«C:UsersCDesktopFOLDER») Then​ переписываю руками:​
​Excel​ переменную хочу обращаться​
​Я общаюсь не​​ доводы отчасти верны,​ чем полностью​ нет, т.к. функции​Чем вам Dir​Debug.Print fn​oExcel.Application.Run «‘111.xls’!ГЊГ*êðîñ1″сделала свою​
​ WorkSheets сделать активным,​ подсвечена серым и​» и нажмите​В появившемся меню кликните​Источник: https://www.ablebits.com/office-addins-blog/2013/12/06/add-run-vba-macro-excel/​
​ VBA (окно​​ Get_Folder = «C:UsersCDesktopFOLDER»​
​2 путь:​`ем играть.​ к этой книге​ только (и уже​ но не для​Цитата​ все равно, откуда​ не угодил?​
​fn = Dir​​ работу. А Вам,​ а не всю​ не работает как​Enter​Insert​
​Перевел: Антон Андронов​Module1​ Else ‘ Get_Folder​smile​Sub MyCode ()​Странно, у меня​Юрий М​ не столько) на​ всех случаев​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Можно написать на​ она вызывается. Думаю,​Похоже, изначально не​Loop​ Ципихович Эндрю, очень​ книгу) . Или​ быть?​– в результате​и в раскрывшемся​Автор: Антон Андронов​).​ = «Y:PublicFolder1» End​ ChDir _ «Y:PublicFolder1″​shift​: Обращайтесь — кто​ форумах по эксель,​для каких случаев​ 10 страниц «правильного»​ несложно удалить из​ правильно понял вас.​
​End With​​ БОЛЬШОЕ СПАСИБО за​ ещё попроще, может​
​Юрик​ будет выведено текущее​ меню выберите​В этой главе даётся​Подсказка:​ If Set FSO​ Workbooks.Open Filename:= _​smile
​позволяет открыть файл​​ мешает? ) Public​ и почему то​ мои доводы не​
​ кода, а можно​ коллекции лишний Item.​ В данном случае,​Ну и собственно,​ помощь!!!​ после открытия книги,​
​: Меню: Сервис -​ значение переменной​Userform​ очень краткий обзор​Как увеличить скорость​ = Nothing End​ «Y:PublicFolder1FILENew.xls» дальше код​ в​ Wb As Workbook​

excelworld.ru

Как открыть книгу Excel в VBA

​ везде (кроме известных​​ верны?​ то же действие​KuklP​ мне караз таки​ открытие книги по​

​Ципихович Эндрю​​ можно как то​ Макрос — Редактор​j​,​
​ редактора Visual Basic​ выполнения макроса?​ Function​

​ работы с открытым​​Excel​ Sub Макрос1() Workbooks.Open​

​ мне форумов по​​KuklP​ описать одной строкой.​: Саша, ты из​

​ было удобнее воспользоваться​​ названию файла и​

​: если обращаетесь к​​ запустить макрос написанный​ Visual Basic.​.​Module​ в Excel. Если​
​В самом начале кода​В принципе я почти​ файлом​без автозапуска макросов​ Filename:=»D:ОтчетыСостояние ТС.xlsm» Set​ эксель) правильность одна.​: Саш, ты посмотри​

​опиши одной строкой​​ пушки по воробьям​ однострочным if, дабы​ папки активной:​ этому обекту тогда​ уже в Excel,​
​Или просто Alt​Чтобы открыть окно​или​

​ Вы любознательный читатель​​ Вашего макроса VBA​ во всём разобрался,​Вопрос: можно ли​IvanOK​ Wb = ActiveWorkbook​

​ Я никому не​​ на себя со​ алгоритм сортировки (без​ стреляешь. Миша пишет:​ не закрывать, а​Код200?’200px’:»+(this.scrollHeight+5)+’px’);»>Set wb =​ КОНЕЧНО перед каждой​ а там уже​ — F11.​

​Locals​​Class Module​
​ и хотите узнать​ должны содержаться строки:​ осталось только понять,​ каким-то образом прописать​: открылось когда жал​ MsgBox Wb.Name End​

​ навязывал, даже не​​ стороны. Ты упорно​ выгрузки на лист)​Т.е. первый же​ перенос для наглядности.​ Workbooks.Open(ActiveWorkbook.Path & «»​ командой ставить oExcel!!!!!​ на много проще?​Саня​, нажмите​:)

​.​​ еще больше информации​Application.ScreenUpdating = False​ как не стирать​

​ оба пути, чтобы​​ шифт в самом​ Sub​ обсуждал этот вопрос​ пытаешься доказать всем​Цитата​:)

​ файл с несовпадающим​​Кстати, проверки названий​

planetaexcel.ru

Как открыть форму, а Excel скрыть или вовсе не открывать

​ & fn)​​S_e_m​S_e_m​: Хм… Вообще, если​Locals Window​Для каждого из описанных​ о редакторе, то​Application.Calculation = xlCalculationManual​ содержимое файла, при​ при обращении по​ экселе Файл-открыть, а​

​KL​​ (с совершенно посторонними​
​ участникам темы, что​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Что легче можно​

​ именем — нужный.​​ файлов на самого​

​—​​: С ВБ 6.0​​: Я очень прошу,​​ я не ошибаюсь,​
​в меню​ выше объектов предусмотрено​ при желании без​​Если таких строк нет,​
​ повторном запуске программы.​​ первому пути (через​ не щелкая по​​: Или даже так:​

​ людьми), но исходя​​ твой громоздкий, глючный​ будет понять и​ Вариант Vitalts гораздо​

​ себя у вас​​PS: что-то код​ закончил. Перекинулся на​ помогите с задачкой:​

​ то в MS​​View​ специальное окно, в​

​ проблем найдете ресурсы​​ то обязательно добавьте​ Практически уверен, что​ диск С), если​ самому файлу)))​Public Wb As​ из их сообщений,​ в таком виде​ отредактировать?​ лучше подходит для​ нет.​ при каждом релоаде​ ВБ .Нет 2010​

​ 1) та что​​ Office есть такая​​редактора Visual Basic.​​ котором будет создаваться​ с более подробным​ следующие строки в​
​ всё дело вот​ файл найден, продолжалась​
​IvanOK​ Workbook Sub Макрос1()​​ очевидно, что правильность​​ код лучше, чем​
​подозреваю, что эту​​ этого случая и​​Michael_S​ по разному кажет,​​ (по работе надо).​​ нужно, книга открылась.​

​ фишка — макросы.​​ В этом окне​ и храниться новый​ описанием.​ свой макрос, чтобы​ в этой строке:​

​ работа, а, если​​: при етом коде​ Set Wb =​ одна. Это видно​ пятистрочный код Vitalts.​ длинную строку будет​ не привлекает внешних​: Vitalts, в вашем​ пофиксил форматирование​ Никак не получается​ 2) Нужно скопировать​
​ Вот эти макросы​ отображаются все переменные,​ код VBA. Порядок​Простейший способ запустить редактор​

​ он работал быстрее​​oExcel = CreateObject(«Excel.Application»)​​ не найден, обращение​​ появляется ексель, потом​
​ Workbooks.Open (Filename:=»D:ОтчетыСостояние ТС.xlsm»)​ по коду, по​

​Я понимаю, если​​ сложнее понять и​​ библиотек. Я уж​​ варианте не хочет​
​nerv​​ с таким кодом->​ с этой книги​
​ пишутся на VB.​ объявленные в текущей​ при этом такой:​ Visual Basic в​ (см. рисунок выше):​Ведь тут явно​ происходило по второму​

​ исчезает, потом появляется​​ MsgBox Wb.Name End​ его стилю. Т.е.​ бы ты девушке,​ отредактировать, чем много​ не говорю о​​ открывать файл (error)​​: Зачем же такие​Dim exl As​ диапазон ячеек 3)​ Но что бы​ процедуре. Окно делится​
​Код, который относится к​ Excel – нажать​В самое начало кода​ создаётся новый файл.​ пути и далее,​ сама форма, а​ Sub​ все хорошие прогеры​ далекой от Экса,​

CyberForum.ru

2 возможных пути открытия файла в VBA

​ правильных/правильно_отформатированных строк​​ размере кода.​
​nerv, Саш, в​ извороты? не проще​
​ Object Dim xlUp​ вставить в другой​ Exel’ем открыть проект…​ на столбцы, в​
​ рабочей книге, должен​ комбинацию клавиш​ после всех строк,​ На что её​ опять же, продолжалась​ есель исчезает как​KL​ видя код говорят,​ это доказывал. Или​Цитата​nerv​
​ вашем варианте жалуется​ воспользоватся многострочным If?​ As Object Dim​
​ файл ексель этот​
​ ну тока если​ которых содержатся имя,​ быть введён в​Alt+F11​ начинающихся с​ нужно заменить, чтобы​ работа.​
​ ето избежать тоесть​: Кстати, ChDir для​ «что такое хорошо,​ ты всех нас​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Ведро картошки можно​
​: Я ни в​
​ на​мой велосипед. Особо​ Selection As Object​ диапазон.​ скопировать исходник, создать​ значение и тип​
​ соответствующий объект​(то есть нажать​Dim​ вместо этого открывать​Думалось сделать через​ нужно что бы​ открытия книги таким​ а что такое​ дураками считаешь?​ отвезти на мопеде,​ кого не стреляю,​Mask​ не тестировал, но​
​ Dim xlDown As​Ну честно, очень​ макрос и туда​
​ каждой переменной, и​ЭтаКнига​ клавишу​(если строк, начинающихся​ существующий?​ on error resume​ просто появилась форма​ способом не нужен.​ плохо». Почему надо​Цитата​ не нужен для​ я животных люблю​и что он​ должен работать )​ Object Dim xlAscending​ нужно!!!​
​ код вставить)​

​ эта информация обновляется​​(ThisWorkbook);​​Alt​ с​

​Ev​​ next так:​

​ в невидемом екселепоявилась​​ Он нужен для​
​ делать так, а​(nerv)200?’200px’:»+(this.scrollHeight+5)+’px’);»>для каких случаев​ этого БелАз​Я привел написанный​ должен делать мне​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub Example()​

​ As Object Dim​​Ципихович Эндрю​Тока придётся ещё​
​ автоматически в ходе​

​Код, который относится к​​и, удерживая её,​Dim​: Избыточно объявлять три​Sub MyCode ()​ просто форма​ функции GetOpenFileName, которая,​ не иначе.​ мои доводы не​его можно донести​ мной ранее код​

​ не понятно. У​​Set Folder =​ xlGuess As Object​
​: вижу что файл​ и форму там​ выполнения программы. Окно​

​ рабочему листу, должен​​ нажать клавишу​нет, то вставляем​

​ объектных переменных (oExcel,​​ On error resume​есть ли у​
​ кстати, тоже уже​Цитата​ верны? — и​ в руках, если​ (под свои нужды)​ меня задача -​ GetFileList(«d:Contacts»)​ Dim xlTopToBottom As​в то же​ чертить новую :)​Locals​ быть введён в​F11​ сразу после строки​

​ oBook, oSheet).​​ next ChDir _​
​ кого каки ето​ не нужна, т.к.​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Хочешь быть нарциссом​ правда думаешь, что​ на то пошло.​Цитата​ открыть файл.​End Sub​ Object Dim xlSortNormal​ время вижу​Олег филатов​очень полезно при​ соответствующий объект​

planetaexcel.ru

Visual Basic работа с файлами Excel (открытие на дозапись)

​). После этого откроется​Sub​Вполне достаточно одной…​ «Y:PublicFolder1» Workbooks.Open Filename:=​ варианты решения етой​ уже давно есть​ — ради Бога​ кому-то интересно искать​ Речь не об​
​(KuklP)200?’200px’:»+(this.scrollHeight+5)+’px’);»>Т.е. первый же​
​За помощь спасибо.​’ —————————————-​ As Object Sub​нестыковка​: Вот Вам руководство​ отладке кода VBA.​

​Лист​​ окно редактора Visual​):​.​
​ _ «Y:PublicFolder1FILENew.xls» ChDir​
​ проблемы​

​ Application.FileDialog(msoFileDialogOpen)​

In this Article

  • Opening the Visual Basic Editor
    • To enable the Developer Ribbon
  • Understanding the VBE Screen
    • Inserting a module or form into your code
    • Removing a Module or Form from the Project Explorer
    • The Properties Window
    • The Code Window
  • Understanding the Code
    • Sub Procedures
    • Function Procedures
  • Creating a new Procedure
  • Writing Code that is easy to understand and navigate
    • Adding Comments
    • Indenting
    • UpperCase vs LowerCase
    • AutoComplete
  • Error trapping and Debugging
    • Syntax errors
    • Compilation Errors
    • Runtime Errors
    • Logical Errors
    • On Error Go To
    • On Error Resume Next

This tutorial will show you how to open and program in the Visual Basic Editor in VBA.

Opening the Visual Basic Editor

There are a few ways to access the Visual Basic Editor (VBE) in Excel.

Press Alt + F11 on your keyboard.

OR

Click View > Macros > View Macros. From here you can Edit an existing macro or Create a new one. Either option opens up the VB Editor.

vba vbe editor

OR

Developer > Visual Basic

Note: If you don’t see the Developer Ribbon, you’ll need to enable it.

To enable the Developer Ribbon

Click on the File tab in the Ribbon, and go down to Options. In the Customize Ribbon options, tick the Developer check box. This is switched off by default so you will need to switch it on to see the tab on the ribbon.

vba vbe developer

Click OK.

The Developer tab will appear on the main ribbon. Click on Visual Basic at the start of the ribbon to access the Visual Basic Editor.

vba vbe vbescreen

Understanding the VBE Screen

The VBE Screen is shown in the graphic below.

vba vbe vbeexplain

The Project Explorer

The Project Explorer enables you to see how the Project in which you are working is organized.  You can see how many modules and forms are stored in the project, and can navigate between these modules and forms. A module is where the code in your workbook is stored, when you record a macro, it will be stored in a standard module – which will by default be named ‘Module1’.

Each of the worksheets in your Excel file also has module behind it, as does the workbook itself.  When you insert a new sheet into the workbook via the main Excel screen, you will see an additional sheet module appear in the Project Explorer.

vba vbe sheetmodule

Double-click on a module to move to the code for that module.

vba vbe workbook module

You can also click on the Window menu on the toolbar and select the module there to move to the code for that module.

vba vbe insert window module

Type of Modules

The modules are organized into 5 different types.

  1. Standard modules – most of your code will go into this type of module. When you record a macro, it gets put into a standard module.    When you write a general procedure to be used throughout your workbook, it also normally goes into a standard module.
  2. Workbook modules – this module holds the code the is unique to that individual workbook. Most of the code in these type of modules are known as EVENTS.   An event can occur when a workbook is opened or closed for example. The module can also contain code that is written by yourself and used by the events.
  3. Sheet modules – this module holds the code that is unique to that individual sheet.  They can occur when a sheet is clicked on for example (the Click Event), or when you change data in a cell.  This module can also hold code that is written by yourself and called by the Events.
  4. Form modules – this is the module behind a custom form that you may create. For example you may create a form to hold details for an invoice, with an OK button, the code behind the button (the Click Event) contains the code that will run  when the button is clicked.
  5. Class modules – this module is used to create objects at run time. Class module are used by Advanced VBA programmers and will be covered at a later stage.

Inserting a module or form into your code

To insert a new module into your code, click on the Insert option on the menu bar, and click Module.

vba vbe insert module

Or, click on the Insert Module button which you will find on the standard ribbon.

vba vbe insert module ribbon

To insert a new user form into your code, select the UserForm option.

vba vbe insert userform

A new user form will appear in the Project Explorer and will be shown in the Code Window on the right.

vba vbe userform

You can also insert a Class Module

vba vbe insert classmodule

A class module is used to insert objects into your VBA project.

vba vbe insert classmodule2

Removing a Module or Form from the Project Explorer

Right-click on the module or form you wish to remove to show the right click short cut menu.

vba vbe delete userform

Click Remove (in this case UserForm1…)

OR

Click on the File menu, and then click on Remove (UserForm1).

vba vbe delete userform 1

A warning box will appear asking if you want to Export the form or module before you remove it.  Exporting the form or module enables you to save it as an individual file for use in a different Excel project at some other time.

vba vbe save userform

More often than not when you remove a module or form it is because you do not need it, so click No.

The Properties Window

You will see the properties window below the Project Explorer.  You may need to switch this on.

Press F4 or click View, Properties Window.

vba vbe properties

The properties window enables you to see the properties for the particular module or form that is selected in the Project Explorer.  When you are working in modules, you can use the properties window to change the name of the module.  This is the only property available to a module. However, when you are working with forms, there will be far more properties available and the Properties window is then used extensively to control the behavior of forms and the controls contained in the form.

When you record a macro, it is automatically put into a standard module.  The module will named ‘Module1’ and any code that is contained in that module is available to be used throughout your project.  You should rename your module to something that is significant, that would make your code easy to find if you were to add multiple modules to the project.

vba vbe properties window

You can also rename your forms.

vba vbe rename forms

If you have renamed your sheet in Excel, the name of the sheet will show up as the name of the sheet in brackets after Sheet1.

vba vbe sheet name

If you want to change the name of the module behind the sheet, you can change it in the same way you change the module and user form name – by changing the Name property in the Properties Window.

vba vbe sheet rename

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

The Code Window

The code window shows you the sub procedures and functions that are contained in your modules – it shows you the actual code.  When you record a macro, a sub procedure will be created for you.  If you add a short cut key to the macro, it will show up as a comment in the macro to let you know what the short cut key is that you assigned to the macro.

vba vbe code window

At the top of the code window are two combo boxes.  These allow you to see which object (if any) within the Module that you might be working on, and which Procedure you might be working on.

In the example above, we are not working on any object – thus this is set to general, but we are working within the Gridlines procedure.

If we had more than one procedure in this module, we could use the combo box above to navigate to the other procedures.

Understanding the Code

There are 2 types of procedures – Sub procedures and Function procedures.

Sub Procedures

The macro recorder can only record Sub procedures.  A Sub procedure does things.  They perform actions such as formatting a table or creating a pivot table, or in the gridline example, changing the view settings of your active window.  The majority of procedures written are Sub procedures.  All macros are Sub procedures.

A sub procedure begins with a Sub statement and ends with an End Sub statement.  The procedure name is always followed by parentheses.

Sub HideGridLines()
   ActiveWindow.DisplayGridlines  = False
End Sub

VBA Programming | Code Generator does work for you!

Function Procedures

A Function procedure returns a value.  This value may be a single value, an array, a range of cells or an object.  Functions usually perform some type of calculation.   Functions in Excel can be used with the Function Wizard or they can be called from Sub Procedures.

Function Kilos(pounds as Double)
  Kilos = (pounds/2.2)
End Function

 This function could be used within the Insert Function dialog box in Excel to convert Pounds to Kilograms.

vba vbe insert function excel

Creating a new Procedure

Before you create your new procedure, make sure you are in the module in which you wish to store the procedure.  You can create a new procedure by clicking on the Insert menu, Procedure;

vba vbe insert procedure

or you can click on the icon on the toolbar

vba vbe insert procedure 2

The following dialog box will appear

vba vbe add procedure

  1. Type the name of your new procedure in the name box – this must start with a letter of the alphabet and can contain letters and number and be a maximum of 64 characters.
  2. You can have a Sub procedure, a Function procedure or a Property procedure. (Properties are used in Class modules and set properties for ActiveX controls that you may have created).
  3. You can make the scope of the procedure either Public or Private. If the procedure is public (default), then it can be used by all the modules in the project while if the procedure is private, it will only be able to be used by this module.
  4. You can declare local variables in this procedure as Statics (this is to do with the Scope of the variable and makes a local procedure level variable public to the entire module). We will not use this option.

When you have filled in all the relevant details, click on OK.

vba vbe public sub proceduire

You then type your code between the Sub and End Sub statements.

ALTERNATIVELY – you can type the Sub and End Sub statements in your module exactly as it appears above.  You do not need to put the word Public in front of the word sub – if this word is omitted, all procedures in the module are automatically assumed to be Public.

Then you type Sub and then the name of your procedure followed by parenthesis.

ie:

Sub test()

The End Sub statement will appear automatically.

vba vbe sub procedure

Writing Code that is easy to understand and navigate

Get into the habit of putting in comments in your code in order to remind yourself at a later stage of the functionality of the code.

vba vbe code comment

You can insert a comment in your code but typing an apostrophe on the keyboard or you can switch on the Edit toolbar, and use the comment button which appears on that toolbar.

Right-click on the toolbars.

vba vbe show debug ribbon

Select Edit.

vba vbe debug ribbon

Click on the comment button to insert a comment into your code.

vba vbe comment block

NOTE: You usually only use the comment block button when you have a few lines of code you wish to comment out (and not delete).  It is easier for a single comment to use an apostrophe.

Indenting

A good habit to get into is to indent your code making it easy to read through the code and see the different parts of the code.

vba vbe indent

There can be many levels of indenting, depending on the logic of your code.

vba vbe indent 2

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

UpperCase vs LowerCase

VBA adjusts all code to Proper Case so if you type ALL IN UPPERCASE or all in lowercase it will Readjust Your Code To Be In Proper Case!

AutoComplete

When you adjust your code, you will notice that VBA tries to help you by suggesting the code that you can type.  This is known as AutoComplete.

vbba vbe code case

Error trapping and Debugging

There are 4 types of errors that can occur when you write VBA code – Syntax errors, Compilation errors, Runtime errors and Logical Errors.

Syntax errors

These occur when you write the code incorrectly.   This is largely prevented by VBA by having the Syntax check option switch on.  This is normally on by default but if your is switch off, then switch it on by going to Tools, Options and click Auto Syntax Check.

vba vbe options syntax

If you type the code incorrectly (for example excluding something that should be in the code), a message box will pop up while you are writing the code giving you the opportunity to amend the code.

vba vbe compile error

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Compilation Errors

These occur when something is missing from the code that prevents the code from running.  The error does not come up when you write the code, but it occurs when you try and run the code.

vba vbe compile error 2

Runtime Errors

These occur when you run the code, and the syntax and compilation is correct, but something else occurs to prevent the code from running correctly.

vba vbe debug

In this case, Sheet4 does not exist.  This error message is more useful than the compile error messages as it gives you the opportunity to Debug the code and see why it is not working.

Click Debug. The code will stop at the error and highlight the error in yellow enabling you to correct your error.

vba vbe debug break

Amend Sheet4 to Sheet2 (as Sheet 2 exists and Sheet 4 does not exist).

vba vbe debug fix

Press F5 or click on the Continue button on the toolbar.

vba vbe f5

Logical Errors

These are the most difficult to find.  In their case, the code is written correctly but the actual logic of the code is flawed, so you may not get the result that you want from the code.  For logical errors, error trapping is essential.

There are 2 types of error traps

On Error Go To

The following code is to open the File Open Dialog box – it will give us an error if the user clicks Cancel.

vba vbe logical error 1

When you run the code the File Open dialog box appears.

vba vbe logical error 2

When you then click cancel, the error will occur.

vba vbe logical error 3

The following Error trap will continue the code to the Exit Function of the code, and return message.

This makes use of On Error GoTo to exit the function.

vba vbe logical error 4

When you run the code and click cancel, the message box will appear.

vba vbe logical error 5

On Error Resume Next

If you put the On Error Resume Next Statement into your code, the line that contains the error will be ignored and the code will continue.

For example, if the user clicks Cancel in the code below, the code will not give you a run-time error, it will just end without the code doing anything further.

vba vbe on error resume next

There are times when this is very useful but it can also be very dangerous in some circumstances as it does not return a message as to why you obtained an error.

The first step to working with VBA in Excel is to get yourself familiarized with the Visual Basic Editor (also called the VBA Editor or VB Editor).

In this tutorial, I will cover all there is to know about the VBA Editor and some useful options that you should know when coding in Excel VBA.

What is Visual Basic Editor in Excel?

Visual Basic Editor is a separate application that is a part of Excel and opens whenever you open an Excel workbook. By default, it’s hidden and to access it, you need to activate it.

VB Editor is the place where you keep the VB code.

There are multiple ways you get the code in the VB Editor:

  1. When you record a macro, it automatically creates a new module in the VB Editor and inserts the code in that module.
  2. You can manually type VB code in the VB editor.
  3. You can copy a code from some other workbook or from the internet and paste it in the VB Editor.

Opening the VB Editor

There are various ways to open the Visual Basic Editor in Excel:

  1. Using a Keyboard Shortcut (easiest and fastest)
  2. Using the Developer Tab.
  3. Using the Worksheet Tabs.

Let’s go through each of these quickly.

Keyboard Shortcut to Open the Visual Basic Editor

The easiest way to open the Visual Basic editor is to use the keyboard shortcut – ALT + F11 (hold the ALT key and press the F11 key).

Keyboard Shortcut to open Visual Basic Editor in Excel

As soon as you do this, it will open a separate window for the Visual Basic editor.

This shortcut works as a toggle, so when you use it again, it will take you back to the Excel application (without closing the VB Editor).

The shortcut for the Mac version is Opt + F11 or Fn + Opt + F11

Using the Developer Tab

To open the Visual Basic Editor from the ribbon:

  1. Click the Developer tab (if you don’t see a developer tab, read this on how to get it).
  2. In the Code group, click on Visual Basic.

Visual Basic Editor button in the ribbon

Using the Worksheet Tab

This is a less used method to open the Vb Editor.

Go to any of the worksheet tabs, right-click, and select ‘View Code’.

View code to open the VB Editor

This method wouldn’t just open the VB Editor, it will also take you to the code window for that worksheet object.

This is useful when you want to write code that works only for a specific worksheet. This is usually the case with worksheet events.

Anatomy of the Visual Basic Editor in Excel

When you open the VB Editor for the first time, it may look a bit overwhelming.

There are different options and sections that may seem completely new at first.

Also, it still has an old Excel 97 days look. While Excel has improved tremendously in design and usability over the years, the VB Editor has not seen any change in the way it looks.

In this section, I will take you through the different parts of the Visual Basic Editor application.

Note: When I started using VBA years ago, I was quite overwhelmed with all these new options and windows. But as you get used to working with VBA, you would get comfortable with most of these. And most of the time, you’ll not be required to use all the options, only a hand full.

Below is an image of the different components of the VB Editor. These are then described in detail in the below sections of this tutorial.

Different Parts of the VB Editor in Excel

Now let’s quickly go through each of these components and understand what it does:

Menu Bar

This is where you have all the options that you can use in the VB Editor. It is similar to the Excel ribbon where you have tabs and options with each tab.

You can explore the available options by clicking on each of the menu element.

You will notice that most of the options in VB Editor have keyboard shortcuts mentioned next to it. Once you get used to a few keyboard shortcuts, working with the VB Editor becomes really easy.

Tool Bar

By default, there is a toolbar in the VB Editor which has some useful options that you’re likely to need most often. This is just like the Quick Access Toolbar in Excel. It gives you quick access to some of the useful options.

You can customize it a little by removing or adding options to it (by clicking on the small downward pointing arrow at the end of the toolbar).

Add or Remove options in the toolbar

In most cases, the default toolbar is all you need when working with the VB Editor.

You can move the toolbar above the menu bar by clicking on the three gray dots (at the beginning of the toolbar) and dragging it above the menu bar.

Note: There are four toolbars in the VB Editor – Standard, Debug, Edit, and User form. What you see in the image above (which is also the default) is the standard toolbar. You can access other toolbars by going to the View option and hovering the cursor on the Toolbars option. You can add one or more toolbars to the VB Editor if you want.

Project Explorer

Project Explorer is a window on the left that shows all the objects currently open in Excel.

When you’re working with Excel, every workbook or add-in that is open is a project. And each of these projects can have a collection of objects in it.

For example, in the below image, the Project Explorer shows the two workbooks that are open (Book1 and Book2) and the objects in each workbook (worksheets, ThisWorkbook, and Module in Book1).

There is a plus icon to the left of objects that you can use to collapse the list of objects or expand and see the complete list of objects.

Project Explorer in Excel VBA Editor

The following objects can be a part of the Project Explorer:

  1. All open Workbooks – within each workbook (which is also called a project), you can have the following objects:
    • Worksheet object for each worksheet in the workbook
    • ThisWorkbook object which represents the workbook itself
    • Chartsheet object for each chart sheet (these are not as common as worksheets)
    • Modules – This is where the code that is generated with a macro recorder goes. You can also write or copy-paste VBA code here.
  2. All open Add-ins

Consider the Project Explorer as a place that outlines all the objects open in Excel at the given time.

The keyboard shortcut to open the Project Explorer is Control + R (hold the control key and then press R). To close it, simply click the close icon at the top right of the Project Explorer window.

Note: For every object in Project Explorer, there is a code window in which you can write the code (or copy and paste it from somewhere). The code window appears when you double click on the object.

Properties Window

Properties window is where you get to see the properties of the select object. If you don’t have the Properties window already, you can get it by using the keyboard shortcut F4 (or go to the View tab and click Properties window).

Properties window is a floating window which you can dock in the VB Editor. In the below example, I have docked it just below the Project Explorer.

Properties Window is docked below Project Explorer

Properties window allows us to change the properties of a selected object. For example, if I want to make a worksheet hidden (or very hidden), I can do that by changing the Visible Property of the selected worksheet object.

Changing the Visible Property of the Worksheet in Properties Window

Related: Hiding a Worksheet in Excel (that can not be un-hidden easily)

Code Window

There is a code window for each object that is listed in the Project Explorer. You can open the code window for an object by double-clicking on it in the Project Explorer area.

Code window is where you’ll write your code or copy paste a code from somewhere else.

When you record a macro, the code for it goes into the code window of a module. Excel automatically inserts a module to place the code in it when recording a macro.

Related: How to Run a Macro (VBA Code) in Excel.

Immediate Window

The Immediate window is mostly used when debugging code. One way I use the Immediate window is by using a Print.Debug statement within the code and then run the code.

It helps me to debug the code and determine where my code gets stuck. If I get the result of Print.Debug in the immediate window, I know the code worked at least till that line.

If you’re new to VBA coding, it may take you some time to be able to use the immediate window for debugging.

By default, the immediate window is not visible in the VB Editor. You can get it by using the keyboard shortcut Control + G (or can go to the View tab and click on ‘Immediate Window’).

Where to Add Code in the VB Editor

I hope you now have a basic understanding of what VB Editor is and what all parts it has.

In this section of this tutorial, I will show you where to add a VBA code in the Visual Basic Editor.

There are two places where you can add the VBA code in Excel:

  1. The code window for an object. These objects can be a workbook, worksheet, User Form, etc.
  2. The code window of a module.

Module Code Window Vs Object Code Window

Let me first quickly clear the difference between adding a code in a module vs adding a code in an object code window.

When you add a code to any of the objects, it’s dependent on some action of that object that will trigger that code. For example, if you want to unhide all the worksheets in a workbook as soon as you open that workbook, then the code would go in the ThisWorkbook object (which represents the workbook).

The trigger, in this case, is opening the workbook.

Similarly, if you want to protect a worksheet as soon as some other worksheet is activated, the code for that would go in the worksheet code window.

These triggers are called events and you can associate a code to be executed when an event occurs.

Related: Learn more about Events in VBA.

On the contrary, the code in the module needs to be executed either manually (or it can be called from other subroutines as well).

When you record a macro, Excel automatically creates a module and inserts the recorded macro code in it. Now if you have to run this code, you need to manually execute the macro.

Adding VBA Code in Module

While recording a macro automatically creates a module and inserts the code in it, there are some limitations when using a macro recorder. For example, it can not use loops or If Then Else conditions.

In such cases, it’s better to either copy and paste the code manually or write the code yourself.

A module can be used to hold the following types of VBA codes:

  1. Declarations: You can declare variables in a module. Declaring variables allows you to specify what type of data a variable can hold. You can declare a variable for a sub-routine only or for all sub-routines in the module (or all modules)
  2. Subroutines (Procedures): This is the code that has the steps you want VBA to perform.
  3. Function Procedures: This is a code that returns a single value and you can use it to create custom functions (also called User Defined Functions or UDFs in VBA)

By default, a module is not a part of the workbook. You need to insert it first before using it.

Adding a Module in the VB Editor

Below are the steps to add a module:

  1. Right-click on any object of the workbook (in which you want the module).Right click on any object
  2. Hover the cursor on the Insert option.
  3. Click on Module.Click on Module

This would instantly create a folder called Module and insert an object called Module 1. If you already have a module inserted, the above steps would insert another module.

Inserted Module in the VB Editor

Once the module is inserted, you can double click on the module object in the Project Explorer and it will open the code window for it.

Now you can copy-paste the code or write it yourself.

Removing the Module

Below are the steps to remove a module in Excel VBA:

  1. Right-click on the module that you want to remove.
  2. Click on Remove Module option.Remove Module for a Project in the VB Editor
  3. In the dialog box that opens, click on No.Prompt before a module is deleted

Note: You can export a module before removing it. It gets saved as a .bas file and you can import it in some other project. To export a module, right-click on the module and click on ‘Export file’.

Adding Code to the Object Code Window

To open the code window for an object, simply double-click on it.

When it opens, you can enter the code manually or copy-paste the code from other modules or from the internet.

Note that some of the objects allow you to choose the event for which you want to write the code.

For example, if you want to write a code for something to happen when selection is changed in the worksheet, you need to first select worksheets from the drop-down at the top left of the code window and then select the change event from the drop-down on the right.

Selection Change Event in VBA Code Window

Note: These events are specific to the object. When you open the code window for a workbook, you will see the events related to the workbook object. When you open the code window for a worksheet, you will see the events related to the worksheet object.

Customizing the VB Editor

While the default settings of the Visual Basic Editor are good enough for most users, it does allow you to further customize the interface and a few functionalities.

In this section of the tutorial, I will show you all the options you have when customizing the VB Editor.

To customize the VB Editor environment, click Tools in the menu bar and then click on Options.

This would open the Options dialog box which will give you all the customization options in the VB Editor. The ‘Options’ dialog box has four tabs (as shown below) that have various customizations options for the Visual Basic Editor.

Options to customize the Vb Editor

Let’s quickly go through each of these tabs and the important options in each.

Editor Tab

While the inbuilt settings work fine in most cases, let me still go through the options in this tab.

As you get more proficient working with VBA in Excel, you may want to customize the VB Editor using some of these options.

Auto Syntax Check

When working with VBA in Excel, as soon as you make a syntax error, you will be greeted by a pop-up dialog box (with some description about the error). Something as shown below:

Auto Syntax Check in Visual Basic Editor Options

If you disable this option, this pop-up box will not appear even when you make a syntax error. However, there would be a change in color in the code text to indicate that there is an error.

If you’re a beginner, I recommend you keep this option enabled. As you get more experienced with coding, you may start finding these pop-up boxes irritating, and then you can disable this option.

Require Variable Declaration

This is one option I recommend enabling.

When you’re working with VBA, you would be using variables to hold different data types and objects.

When you enable this option, it automatically inserts the ‘Option Explicit’ statement at the top of the code window. This forces you to declare all the variables that you’re using in your code. If you don’t declare a variable and try to execute the code, it will show an error (as shown below).

Varibale Not Declared Error in Excel VBA

In the above case, I used the variable Var, but I didn’t declare it. So when I try to run the code, it shows an error.

This option is quite useful when you have a lot of variables. It often helps me find misspelled variables names as they are considered as undeclared and an error is shown.

Note: When you enable this option, it does not impact the existing modules.

Auto List Member

This option is quite useful as it helps you get a list of properties of methods for an object.

For example, if I want to delete a worksheet (Sheet1), I need to use the line Sheet1.Delete.

While I am typing the code, as soon as I type the dot, it will show me all the methods and properties associated with the Worksheet object (as shown below).

Autolist Member Option in VB Editor

Auto list feature is great as it allows you to:

  • Quickly select the property and method from the list and saves time
  • Shows you all the properties and methods which you may not be aware of
  • Avoid making spelling errors

This option is enabled by default and I recommend keeping it that way.

Auto Quick Info Options

When you type a function in Excel worksheet, it shows you some information about the function – such as the arguments it takes.

Similarly, when you type a function in VBA, it shows you some information (as shown below). But for that to happen, you need to make sure the Auto Quick Info option is enabled (which it is by default).

Auto Quick Info Option in VB Editor

Auto Data Tips Options

When you’re going through your code line by line and place your cursor above a variable name, it will show you the value of the variable.

I find it quite useful when debugging the code or going through the code line by line which has loops in it.

Auto Data Tips Option in Visual Basic Editor Options

In the above example, as soon as I put the cursor over the variable (var), it shows the value it holds.

This option is enabled by default and I recommend you keep it that way.

Auto Indent

Since VBA codes can get long and messy, using indentation increases the readability of the code.

When writing code, you can indent using the tab key.

This option ensures that when you are done with the indented line and hit enter, the next line doesn’t start from the very beginning, but has the same indentation as the previous line.

Indentation enabled in the VB Editor code windows

In the above example, after I write the Debug.Print line and hit enter, it will start right below it (with the same indentation level).

I find this option useful and turning this off would mean manually indenting each line in a block of code that I want indented.

You can change the indentation value if you want. I keep it at the default value.

Drag and Drop Text Editing

When this option is enabled, it allows you to select a block of code and drag and drop it.

It saves time as you don’t have to first cut and then paste it. You can simply select and drag it.

This option is enabled by default and I recommend you keep it that way.

Default to Full Module View

When this option is enabled, you will be able to see all the procedures in a module in one single scrollable list.

If you disable this option, you will only be able to see one module at a time. You will have to make a selection of the module you want to see from the drop-down at the top right of the code window.

This option is enabled by default and I recommend keeping it that way.

One reason you may want to disable it when you have multiple procedures that are huge and scrolling across these is taking time, or when you have a lot of procedures and you want to quickly find it instead of wasting time in scrolling.

Procedure Separator

When this option is enabled, you will see a line (a kind of divider) between two procedures.

I find this useful as it visually shows when one procedure ends and the other one starts.

Procedure Separator Option in VB Editor

It’s enabled by default and I recommend keeping it that way.

Editor Format Tab

With the options in the Editor Format tab, you can customize the way your code looks in the code window.

Personally, I keep all the default options as I am fine with it. If you want, you can tweak this based on your preference.

To make a change, you need to first select an option in the Code Colors box. Once an option is selected, you can modify the foreground, background, and indicator color for it.

The font type and font size can also be set in this tab. It’s recommended to use a fixed-width font such as Courier New, as it makes the code more readable.

Note that the font type and size setting will remain the same for all code types (i.e., all the code types shown in the code color box).

Below is an image where I have selected Breakpoint, and I can change the formatting of it.

Editor Format Options in VB Editor

Note: The Margin Indicator Bar option when enabled shows a little margin bar to the left of the code. It’s helpful as it shows useful indicators when executing the code. In the above example, when you set a breakpoint, it will automatically show a red dot to the left of the line in the margin bar. Alternatively, to set a breakpoint, you can simply click on the margin bar on the left of the code line that you want as the breakpoint.

By default, Margin Indicator Bar is enabled and I recommend keeping it that way.

One of my VBA course students found this customization options useful and she was color blind. Using the options here, she was able to set the color and formats that made it easy for her to work with VBA.

General Tab

The General tab has many options but you don’t need to change any of it.

I recommend you keep all the options as is.

One important option to know about in this tab is Error Handling.

By default, ‘Break on Unhandled Errors’ is selected and I recommend keeping it that way.

This option means that if your code encounters an error, and you have not handled that error in your code already, then it will break and stop. But if you have addressed the error (such as by using On Error Resume Next or On Error Goto options), then it will not break (as the errors are not unhandled).

Docking Tab

In this tab, you can specify which windows you want to get docked.

Docking means that you can fix the position of a window (such as project explorer or the Properties window) so that it doesn’t float around and you can view all the different windows at the same time.

If you don’t dock, you will be able to view one window at a time in full-screen mode and will have to switch to the other one.

I recommend keeping the default settings.

Other Excel tutorials you may like:

  • How to Remove Macros From an Excel Workbook
  • Comments in Excel VBA (Add, Remove, Block Commenting)
  • Using Active Cell in VBA in Excel (Examples)

В этой главе даётся очень краткий обзор редактора Visual Basic в Excel. Если Вы любознательный читатель и хотите узнать еще больше информации о редакторе, то при желании без проблем найдете ресурсы с более подробным описанием.

Содержание

  1. Запуск редактора Visual Basic
  2. Окна редактора Visual Basic
  3. Окно проекта (Project)
  4. Окно кода (Code)
  5. Окно свойств (Properties)
  6. Окно отладчика (Immediate)
  7. Окно переменных (Locals)
  8. Окно отслеживания (Watches)

Запуск редактора Visual Basic

Простейший способ запустить редактор Visual Basic в Excel – нажать комбинацию клавиш Alt+F11 (то есть нажать клавишу Alt и, удерживая её, нажать клавишу F11). После этого откроется окно редактора Visual Basic, как показано на картинке ниже. Имейте ввиду, что окно Excel остается открытым и находится позади окна редактора.

Редактор Visual Basic в Excel

Окна редактора Visual Basic

В процессе работы в редакторе Visual Basic в Excel могут быть открыты различные окна. Управление окнами осуществляется в меню View, которое находится в верхней части окна редактора VBA. Ниже дано описание отдельных окон.

Окно проекта (Project)

Окно Project открывается в левой части редактора VBA (показано на картинке выше). В этом окне для каждой открытой рабочей книги создаётся проект VBA (VBA Project). Проект VBA – это набор всех объектов и модулей VBA, привязанных к текущей книге. Изначально в него входят:

  • Объект ЭтаКнига (ThisWorkbook), привязанный к книге Excel;
  • Объекты Лист (Sheet), привязанные к каждому листу текущей рабочей книги Excel.Редактор Visual Basic в Excel

Самостоятельно в проект можно добавить объекты Userform, Module и Class Module. Если Вы посмотрите на картинку выше, то увидите, что в проект VBA для книги Book1.xlsm добавлен объект Module с названием Module1.

Вот как можно создать новый объект Userform, Module или Class Module:

  • В окне Project выберите рабочую книгу, в которую нужно добавить объект, и кликните по ней правой кнопкой мыши.
  • В появившемся меню кликните Insert и в раскрывшемся меню выберите Userform, Module или Class Module.

Для каждого из описанных выше объектов предусмотрено специальное окно, в котором будет создаваться и храниться новый код VBA. Порядок при этом такой:

  • Код, который относится к рабочей книге, должен быть введён в соответствующий объект ЭтаКнига (ThisWorkbook);
  • Код, который относится к рабочему листу, должен быть введён в соответствующий объект Лист (Sheet);
  • Код более общего характера должен быть введён в Module;
  • Код для нового объекта должен быть введён в Class Module;
  • Если нужно создать диалоговое окно для взаимодействия с пользователем, то можно использовать Userform.

Окно кода (Code)

Двойной щелчок мышью по любому объекту в окне Project открывает соответствующее окно Code, предназначенное для ввода кода VBA с клавиатуры. На одном из приведённых выше рисунков показано окно кода для Module1.

По мере ввода кода VBA в окно Code, редактор Visual Basic следит за правильностью ввода, ищет ошибки в коде и выделяет код, который требует исправления.

Окно свойств (Properties)

В окне Properties перечислены свойства объекта, который в момент создания (не в процессе выполнения программы) выделен в окне проекта. Эти свойства могут быть различными в зависимости от типа выделенного объекта (лист, книга, модуль и другие).

Редактор Visual Basic в Excel

Окно отладчика (Immediate)

Окно Immediate можно отобразить в редакторе Visual Basic через меню View > Immediate Window или нажатием комбинации клавиш Ctrl+G. Это окно помогает при отладке кода. Оно выполняет роль области вывода для отладки выражений и позволяет вычислять отдельные выражения или выполнять строки кода по одной.

Например, введите выражение «?j» и нажмите Enter – в результате будет выведено текущее значение переменной j.

Редактор Visual Basic в Excel

Окно переменных (Locals)

Чтобы открыть окно Locals, нажмите Locals Window в меню View редактора Visual Basic. В этом окне отображаются все переменные, объявленные в текущей процедуре. Окно делится на столбцы, в которых содержатся имя, значение и тип каждой переменной, и эта информация обновляется автоматически в ходе выполнения программы. Окно Locals очень полезно при отладке кода VBA.

Редактор Visual Basic в Excel

Окно отслеживания (Watches)

Окно Watches также очень помогает при отладке кода VBA, так как в нём можно увидеть значение, тип и контекст любого отслеживаемого выражения, которое задаст пользователь. Чтобы открыть окно Watches, нажмите Watch Window в меню View редактора Visual Basic. Также окно Watches будет открыто автоматически, если задать отслеживаемое выражение.

Редактор Visual Basic в Excel

Чтобы задать отслеживаемое выражение, нужно:

  1. Выделить выражение в редактируемом коде VBA.
  2. В меню Debug редактора VBA нажать Quick Watch.
  3. Нажать Add.

Кроме рассмотренных, в меню редактора Visual Basic в Excel существует ещё множество параметров и команд, используемых при создании, выполнении и отладке кода VBA.

Оцените качество статьи. Нам важно ваше мнение:

Visual Basic for Applications (VBA) is a form of the Visual Basic programming language integrated into all Microsoft Office products. You can create add-on components within your basic Excel 2019 spreadsheet to create additional functionality. VBA can get complicated, but knowing how to create basic code and functionality can improve your spreadsheet’s usefulness and automate certain activity that would take hours of time.

Enabling the Developer Tab in Excel 2019

To use VBA, you need the «Developer» tab enabled. The «Developer» tab has several buttons and features that enhance the way you create spreadsheets. If you don’t have the «Developer» tab enabled, follow these next steps to enable it.

Click the «File» ribbon tab, and then click the «Options» link that shows in the bottom-left section of the Excel window. This opens a new configuration window where you can set preference for different elements of Excel. Click the «Customize Ribbon» option in the left panel.

(Excel options and configuration window)

In the image above, notice that the developer option is checked in the far right panel. This check box enables the «Developer» tab in your Excel view. Click «OK» to enable the tab and return to your Excel 2019 interface.

(VBA button location)

You should now see an additional tab marked «Developer» in the list of Excel 2019 menu options. Click this tab, and you’ll see the VBA button available on the left side.

Creating a Button on Your Spreadsheet

When you want to use VBA on your spreadsheet, buttons are one of the most common elements that you add to your document. With a button, you can trigger an event and use it to perform an action.

Components for VBA actions are found in the «Developer» tab in the «Insert» button dropdown.

(Form and ActiveX components for VBA)

When you click the «Insert» button, a dropdown displays all of the available components that you can add to your spreadsheets. The top-left control in the «Form Controls» section has the button control. You can hover your mouse over each of the components in the list to see what you can add to a spreadsheet. If you are familiar with HTML web page components, then you will recognize most of the available components in the dropdown.

Click the button control and then you can draw the button on your spreadsheet. Drawing a button lets you make it as large as small as you want. After you draw the button, a window opens where you can assign a macro.

(Assign macro window)

Click «OK» and the window closes. Now you see a button on your spreadsheet with the label «Button 1.» You can change the label on the newly created button by right-clicking the button and selecting «Edit Text.» This action prompts you for the new button name. Type a new name for your button. In this example, we’ve used the text «My Button» for the button text.

(A new button with custom text)

You can click the button if you want, and an error message with display telling you that you haven’t created a macro for it yet. This is because you haven’t created the code that will run when the button is clicked. The button serves no purpose, but you can create the macro that runs when it’s pushed, which then removes the error when you click the button.

Right click the button and choose «Assign Macro.» This action opens a Visual Basic for Applications workspace. The workspace is tied to the workbook that you have open, but you can make full applications that tie with your spreadsheet using VBA. In this workspace, you can create, test, and run any code that you assign to components in your application.

Working in the VBA Workspace

The VBA workspace looks the same whether you program macros in Word or Excel. It’s a workspace where you can program the macro and view all other code that you’ve previously created.

(VBA workspace)

The image above shows the VBA workspace. When you right click a component such as a button and choose «Edit Code,» VBA opens to the location where code is triggered when you click the button. VBA gives names to these functions that help you identify what happens should you perform an activity on it. Since a button is usually triggered by a click event, the function is given the original name of the button, an underscore, and then the word «Click.» For your first button created in your spreadsheet, the name for a click event is «Button1_Click()» and you add any code between the «Sub» and «End Sub» phrases.

The «Sub» keyword indicates that you are starting an event. The next part is the name of the event, and the last statement in a trigger event is the «End Sub» statement.

In the left panel of the workspace, you can see other objects in a tree view. The top object is always the workbook. If you recall, a workbook contains worksheet. Under the «Book1» main project header, you see «ThisWorkbook» which represents the workbook that you have opened, and the «Sheet1» represents the worksheet in the workbook. You can write VBA that works directly on a workbook or a worksheet activity such as when you open the workbook, a macro automatically runs.

The «Modules» section holds the files that you store containing VBA code. You can have several of these in your VBA code, or you can just have one file that contains all of the functions used to run macros.

Writing Some Simple VBA Code

With the VBA editor open, you now have a function ready to edit for your button. Anything you type in the «Sub» and «End Sub» statements will run when you click the Button1 component. When you start working with VBA, you want to create easy function statements so that you can follow what is going on as the code runs. In this example, we’ll add some text to a cell within the current spreadsheet.

Within the sub start and end phrases, type the following code:

Sub Button1_Click()

Range(«A1»).Value = «My Test»

End Sub

The code above tells Excel 2019 that you want to change the value contained in the cell «A1» in the current sheet to «My Test.» The «Range» indicates that you want to apply changes to a cell range set in the functions parameters. You can assign any value to a range, but in this example we apply text. Any formatting already set on the cell will also still apply, so if you have a cell set to bold text, then this value will have the bold format applied.

At the top of the VBA workspace, notice that there are three start, pause and stop buttons. You can use these buttons to test your new code. The «start» button will run the current function and apply changes to the spreadsheet, which in this example is changing content to «My Test.»

(The start button in the VBA workspace)

Click the start button and watch the text in the A1 cell change to «My Test.» Should you have a long list of statements within your function, you might want to pause the procedure. The stop button stops execution, so should you resume it then execution will start where it left off. With the pause button, execution resumes where the last statement left off.

The «MsgBox» function is extremely common in any application. The MsgBox function displays a warning or a message to the user. In any software application, you’ve seen pop-up windows that display a message that provides information. Even web applications display messages as pop-ups and warnings. The MsgBox function in VBA is the equivalent of all of these pop-ups that you’ve seen across different applications.

Suppose that you want to show a confirmation to the user that the button’s function completed execution. In this example, only one statement executes, but you might have hundreds of lines of code that must execute and you want to show the user that it’s completed. You might have a procedure that takes an unusual amount of time to complete, so users must wait for it to complete and then you display the message to confirm when the procedure is over.

Add the next line of code to the same VBA function Button1_Click():

Sub Button1_Click()

Range(«A1»).Value = «My Test»

MsgBox «Cell value change finished»

End Sub

In the code above, the cell A1 has its value changed to «My Test.» After the text is changed in the A1 cell, a message box opens and displays the text «Cell value change finished.» This is just a small example of how you can use the MsgBox function. After you finished changing your VBA code, click the play button again. You will see the two statements run, and the program will stop.

After you are finished writing your code, you still need to save it and test it within the spreadsheet. Your users won’t open the VBA workspace, so you need to make sure that the code executes outside of the VBA workspace.

Close the VBA workspace. You now need to assign the macro to the button. Right-click the button and click «Assign Macro.» Choose the Button1_Click value and click «OK.» Should you ever want to go back and change the statements executed by the macro. Use this screen to click the macro name, and then click «Edit» to again open the VBA workspace with the function code shown in the workspace window.

After the window closes, click the button. Notice that the text in cell A1 changes and then a window displays with a message that the procedure has completed. You’ve just created your first VBA macro that runs in your spreadsheet. You can create much more complex applications with VBA that run across several spreadsheets and can affect several other workbooks that aren’t even open on your desktop.

One issue to remember with VBA is that it’s a powerful tool that can do harm if it’s used the wrong way. Malware writers use VBA macros to download malicious software and install it on your computer. When you work with macros, your recipients of any spreadsheet must give your macros permission to run on their machines. Most users are trained not to open spreadsheets with macros, so they are mostly used within the same organization.

Понравилась статья? Поделить с друзьями:
  • Visual basic запись в excel
  • Visual basic для приложений в word
  • Vlookup excel как по русски
  • Vlookup excel in russian
  • Vlookup excel how to use