Vba this excel application

The «Application» is the root of any application where the program code is executing.

It has different meanings with different applications.

For example, with Excel VBA, The «Application» object refers to the entire Excel application.

This means, «Application » object is not bound only to the excel containg macro code.

Similarly, In MS Word, The same «Application» object refers to the entire MS Word.

The same is the case with MS Access VBA too.

There are numerous uses of this object and it offers a large number of functionalities some of which are discussed below:

1.Application.ScreenUpdating

The ScreenUpdating property of Application object is used to set the visual updation of the excel workbook to either TRUE or FALSE.

This property is useful while modifying a workbook with values and then saving it.

In this case, the excel screen will flicker while the program is executing and is not visually pleasing.

So, to avoid this, the ScreenUpdating property has to be set to FALSE.

Application.ScreenUpdating=False

2.Application.DisplayAlerts

This is also a useful member of the Application object.

With this, one can control the display of unwanted alert dialogs, which will hinder the speed of the program.

For example, while deleting a sheet, the excel usually displays a dialog box giving a warning and will proceed further only after an user action of a button click.

So, to avoid this during automation, the «DisplayAlerts» property is used, which if set TRUE, will not show the dialogbox and will automatically accepts the OK button click.

The same is the fact with Saving an excel.

Application.DisplayAlerts=False

If you see at the very first lines of this VBA Editor, you can see these two statements.

A screenshot of this is shown as below:

excel vba application object

You can find similar Excel Questions and Answer hereunder

1) What are the main cell objects in VBA

2) How to print a worksheet in Excel

3) How to do webscrapping in VBA. Here some basics

4) Vba length of an array in Excel

5) Highlight row of selected cell in Excel

6) Vlookup to return multiple values in same cell in Excel

7) How do you close, save, open files and do other operations in the workbook in VBA

8) Vba list all files in a folder in Excel

9) What is a methods. Methods are action that can be performed by an object

10) How to add email and emailing function in Excel VBA

WorksheetFunction | ScreenUpdating | DisplayAlerts | Calculation

The mother of all objects is Excel itself. We call it the Application object. The application object gives access to a lot of Excel related options.

WorksheetFunction

You can use the WorksheetFunction property in Excel VBA to access Excel functions.

1. For example, place a command button on your worksheet and add the following code line:

Range(«A3»).Value = Application.WorksheetFunction.Average(Range(«A1:A2»))

When you click the command button on the worksheet, Excel VBA calculates the average of the values in cell A1 and cell A2 and places the result into cell A3.

WorksheetFunction in Excel VBA

Note: instead of Application.WorksheetFunction.Average, simply use WorksheetFunction.Average. If you look at the formula bar, you can see that the formula itself is not inserted into cell A3. To insert the formula itself into cell A3, use the following code line:

Range(«A3»).Value = «=AVERAGE(A1:A2)»

ScreenUpdating

Sometimes you may find it useful to disable screen updating (to avoid flickering) while executing code. As a result, your code will run faster.

1. For example, place a command button on your worksheet and add the following code lines:

Dim i As Integer

For i = 1 To 10000
    Range(«A1»).Value = i
Next i

When you click the command button on the worksheet, Excel VBA displays each value a tiny fraction of a second and this can take some time.

ScreenUpdating

2. To speed up the process, update the code as follows.

Dim i As Integer

Application.ScreenUpdating = False

For i = 1 To 10000
    Range(«A1»).Value = i
Next i

Application.ScreenUpdating = True

As a result, your code will run much faster and you will only see the end result (10000).

DisplayAlerts

You can instruct Excel VBA not to display alerts while executing code.

1. For example, place a command button on your worksheet and add the following code line:

ActiveWorkbook.Close

When you click the command button on the worksheet, Excel VBA closes your Excel file and asks you to save the changes you made.

DisplayAlerts

2. To instruct Excel VBA not to display this alert while executing code, update the code as follows.

Application.DisplayAlerts = False

ActiveWorkbook.Close

Application.DisplayAlerts = True

As a result, Excel VBA closes your Excel file, without asking you to save the changes you made. Any changes are lost.

Calculation

By default,  calculation is set to automatic. As a result, Excel recalculates the workbook automatically each time a value affecting a formula changes. If your workbook contains many complex formulas, you can speed up your macro by setting calculation to manual.

1. For example, place a command button on your worksheet and add the following code line:

Application.Calculation = xlCalculationManual

When you click the command button on the worksheet, Excel VBA sets calculation to manual.

2. You can verify this by clicking on File, Options, Formulas.

Calculation Options

3. Now when you change the value of cell A1, the value of cell B1 is not recalculated.

Manual Calculation

You can manually recalculate the workbook by pressing F9.

4. In most situations, you will set calculation to automatic again at the end of your code. Simply add the following code line to achieve this.

Application.Calculation = xlCalculationAutomatic

Skip to content

VBA Excel Application Object

  • Excel VBA Application Object

Excel VBA Application object is the one of the most frequently used object while automating any task with VBA. We refer different Excel applications and perform various operations on Excel Workbooks. We have different Properties, Methods to deal with Excel Application Object. Here you can find a brief explanation about each on most useful Properties and Methods while automating any task.

Our objective of building this Excel VBA Explorer is to provide suitable examples on most frequently used methods and properties of Application object. So that you can quickly find the solution, syntax whenever you required it.

Application Object

Application Object refers the entire Microsoft Excel Application. We can use Application Object to deal with Methods and Properties of the Entire Excel Application. Here are some Examples:

'To Disable the Display Alerts
Application.DisplayAlerts=False 

'To Disable the Application Events
Application.EnableEvents=False 

'To Minimize the Application Window
Application.WindowState = xlMaximized 

Methods

Application methods helps us to perform different actions with Excel Workbooks. For example, we can Run a Application and Stop a Application ,etc.

Excel VBA Application Object Methods

  • Calculate: To Calculate all Open Workbook.
  • CalculateFull: To forces full caluculation in all the open Workbook.
  • FindFile: To display open dialog box to open a file.
  • Goto: To select any range.
  • Run: To run a procedure or function.
  • Wait: To stop running macro.

Properties

Properties of Application object will helps us to deal with various properties of Excel Applications. For example, we can change the Application Caption, sets the user name,sets the window state of the Application, etc.

Excel VBA Application Object Properties

  • Calculation: To represent calculation mode.
  • Caption: To represent name of the title bar.
  • DisplayAlerts: To represent display alerts.
  • DisplayFormulaBar:To hide or show the formula bar.
  • DisplayFullScreen:To display Excel screen.
  • DisplayScrollBars:To stop or display scrollbar.
  • DisplayStatusBar:To display status on the status bar.
  • EnableEvents: To enable events.
  • Path: To get the complete path of the application.
  • ScreenUpdating: To turn On/Off screen updating.
  • StatusBar:To sets the text on the status bar.
  • UserName: To sets the name of the user.
  • WindowState:To sets the state of the application window.
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates
    • Application Object
    • Methods
      • Excel VBA Application Object Methods
    • Properties
      • Excel VBA Application Object Properties

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: March 18, 2023

11 Comments

  1. CHANDRAKANT
    January 19, 2015 at 12:09 PM — Reply
  2. Siddu
    April 8, 2015 at 10:26 AM — Reply
    'Display or Hide Scroll Bars:
    'TO DISPLAY
    Application.DisplayScrollBars = True
    'TO HIDE
    Application.DisplayScrollBars = False
    
    
    'Display or Hide Status Bar:
    'TO DISPLAY
    Application.DisplayStatusBar= True
    'TO HIDE
    Application.DisplayStatusBar= False
    
    'To remove last copied data from clipart
    Application.CutCopyMode = False
    
    'TO set reference style in Excel:
    'To set application reference style to R1C1  style
    Application.ReferenceStyle = xlR1C1
    
    'To set application reference style to Range("A1")style
    Application.ReferenceStyle = xlA1
    
    'To hide or unhide the workbook window
    'To make excel window as invisible
    Application.Visible = False
    
    'To make excel window as visible
    Application.Visible = True
    

  3. Venkat
    June 15, 2015 at 7:11 PM — Reply

    Dear Mr.P N Rao ! Your website Analysistab is a wonderful site where one can learn a lot about excel vba.Incase I

  4. Venkat
    June 15, 2015 at 7:11 PM — Reply

    Dear Mr.P N Rao ! Your website Analysistab is a wonderful site where one can learn a lot about excel vba.

  5. PNRao
    June 19, 2015 at 1:49 PM — Reply

    Thanks for the nice feedback Venkat! – PNRao!

  6. koolx
    June 21, 2015 at 2:04 PM — Reply

    I managed to hide the status bar in Excel 2013 using the code below. I can open a new workbook without the status bar. But when I open a saved workbook, it opens the saved workbook and a new workbook. How can I open just the saved workbook alone without opening a new workbook?

    Private Sub Workbook_Open()
    Application.DisplayStatusBar = False
    Workbooks.Add
    ThisWorkbook.Close False
    End Sub
    

  7. Deepa khilani
    July 1, 2015 at 11:00 PM — Reply

    Hi PNRao,

    I want to learn Excel VBA but I can not understand that how can I learn Excel VBA?

  8. PNRao
    July 2, 2015 at 12:16 AM — Reply

    Hi Deepa,
    The best way is to start with simple macros with Macro Recorder and Try to understand the Excel Object Model. You can follow our tutorials where we have provided numerous examples on Excel VBA.

    However, we are going to start our online classes in couple of weeks. You can joint if you are interested.

    Thanks-PNRao!

  9. Dela
    September 11, 2017 at 5:18 PM — Reply

    Hi PNRao,

    How can I pick the data in the cell to a vba variable then display in a text box arranged according to my preference.

  10. PNRao
    September 12, 2017 at 11:30 PM — Reply
    Sub sbPickDataFromCellsofExcelApplication()
    
    'Pick data from a Celll to Variable
    
    myVar = Cells(1, 5) ' this is Row 1 and Column 5
    'Or myVar=Range("E5")
    
    'Assign the Variable value To a Text Box
    
    TextBox1.Text = myVar
    
    'OR You can directly assign the Cell or Range value
    'TextBox1.Text = Cells(1, 5)
    
    End Sub
    
    

  11. Krishna
    April 11, 2020 at 12:38 PM — Reply

    Hi i have 2000 files in which number of column is different few file having 90 column few is 80 columns and column sequence is also not same. i want to consolidate 15 columns from all the files only which is in every excel file and that columns name is also same in each file.
    can you please suggest solutions.

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Обращение к объекту

Контейнеры

Объекты приложения могут включать в себя объекты разных типов. Например, рабочая книга может содержать один или несколько рабочих листов и листов диаграмм. Рабочий лист, в свою очередь, содержит строки, колонки и интервалы ячеек. Когда объект одного типа находится внутри объекта другого типа, говорят о контейнере ( container ), в котором содержится объект.

Самый старший контейнер объектов MS Excel — это приложение Application. Приложение — это контейнер для всех открытых рабочих книг, и в то же время приложение содержит такой глобальный объект, как строка меню, который доступен любой рабочей книге. Рабочий лист представляет пример того, что объект может быть частью нескольких контейнеров или коллекций одновременно: он входит в рабочую книгу, с одной стороны, а с другой стороны — является частью коллекции Sheets и коллекции Worksheets.

Преимущества

  • Рассмотрение объекта в качестве контейнера позволяет уточнить, сославшись на контейнер, с каким именно объектом производится действие в процедуре.

Если в рабочей книге имеются два рабочих листа Sheet1 и Sheet2, то запись Worksheets(«Sheet1»).Range(«A1») указывает на ячейку A1 рабочего листа Sheet1, а запись Worksheets(«Sheet2»).Range(«A1») указывает на ячейку A1 рабочего листа Sheet2.

Ссылка на объект

Объект в VBA указывается при помощи ссылки. Запись Workbookscross«).Worksheets(«Sheet2») указывает на объект, являющийся листом с именем Sheet2 в рабочей книге cross, отличая его, таким образом, от листа с тем же именем, но в другой рабочей книге.

Важно

  • Ссылка на объект состоит из имени контейнера и названия свойства-участника.
  • Ссылка на объект может состоять из нескольких спецификаторов (имен контейнеров), отделенных друг от друга точкой. Такая запись отражает иерархию объектов и позволяет точно указать конкретный объект.
  • Свойства и методы объекта указываются через точку после ссылки на объект.

Для объектов, относящихся к классу globals (например, активная рабочая книга, активная ячейка рабочего листа, константа), спецификатор Application можно опустить.

Оператор With

В VBA перед обращением к каждому из методов или свойств объекта требуется наличие ссылки на объект. Конструкция With…End With позволяет применить последовательность операторов к объекту, указав его имя только один раз в операторе With. Благодаря этому программа становится менее громоздкой, освобождаясь от повторений ссылки на объект.

Синтаксис оператора

With Object
[statements]
End With
  • Objectимя объекта;
  • statementsпоследовательность операторов.

Первая строка этой структуры идентифицирует объект, с которым будут производиться действия. В последующих операторах используются свойства и методы идентифицированного объекта. Оператор End With является закрывающей скобкой для оператора With. Часто подобная структура записывается при помощи макрорекордера.

Внимание

  • Каждый оператор внутри блока statements начинается с точки.

Использование объектных переменных

Чтобы получить доступ к свойствам или методам объекта, можно использовать два способа: прямое указание на объект и применение объектной переменной. Объектная переменная занимает 4 байта и хранит адрес, указывающий на объект.

Например, установить полужирный шрифт для первой строки активного листа можно оператором ActiveSheet.Rows(1).Font.Bold = True или, используя объектную переменную, можно предложить два способа записи:

Здесь оператор Set создает объект, тип которого установлен при описании объектной переменной. Далее можно обратиться к свойствам или методам созданного объекта. В первом случае это объект типа Range, во втором случае — тип объекта Font.

Преимущества

  • Использование объектных переменных улучшает читабельность программы.
  • Использование объектных переменных уменьшает время выполнения программы, т.к. при каждом выполнении оператора для обращения к объекту не придется проходить полную цепочку иерархии объектов.

Объект Application

При открытии MS Excel автоматически становится доступным объект Application с его свойствами и методами. Объект Application — корневой объект приложения. В него вложены остальные объекты приложения. Доступ к ним осуществляется посредством свойств-участников объекта Application.

Для создания ссылки на объект Application используется свойство Application.

Примеры операторов

Application.Windows(«AIR.XLS «).Activate Оператор активизирует рабочую книгу
Application.Goto Range(«B3:C5») Оператор выделяет интервал ячеек на активном рабочем листе

Многие свойства объекта Application используются без ссылки на объект Application, так как они возвращают объекты, относящиеся к классу globals.

Активные объекты

Свойства, название которых начинается со слова Active, возвращают активный объект соответствующего типа. Для этих свойств необязательно указывать ссылку на объект Application, так как они входят в класс globals. Некоторые из этих свойств являются одновременно свойствами нескольких объектов.

Свойства, возвращающие активный или выделенный объект

Свойство Объект Действие Возвращаемый объект
ActiveCell Application, Window Возвращает активную ячейку Range
ActiveSheet Application, Window, Workbook Возвращает активный лист. Это может быть рабочий лист, лист диаграмм Sheet
ActiveWorkbook Application Возвращает активную рабочую книгу Workbook
ActiveWindow Application Возвращает активное окно Window
Selection Application, Window Возвращает выделенный объект Различные типы объектов

Так как перечисленные в таблице свойства возвращают объекты, при записи операторов для активных объектов используются методы или свойства объектов соответствующих типов.

Примеры

Оператор Комментарий
ActiveCell.Font.Bold=True Устанавливает полужирный шрифт текста активной ячейки
ActiveSheet.Name=»Проба» Изменяет название активного листа рабочей книги
MsgBox ActiveWorkbook.Fullname Высвечивает полное имя рабочей книги, включая путь и имя файла
Selection.NumberFormat=»0.00″ Устанавливает числовой формат с двумя знаками после запятой для ячеек выделенного интервала
ActiveCell.Value=10

Application.ActiveCell.Value=10

ActiveWindow.ActiveCell.Value=10

Application.ActiveWindow.ActiveCell.Value=10

Присваивают активной ячейке значение 10. Приведенные примеры доступа к активной ячейке равносильны
Worksheets(«Sheet1»).Activate

Selection.Clear

Очищает предварительно выделенный на листе Sheet1 объект, например, интервал ячеек
Если никакой объект не выделен, то свойство Selection возвращает значение Nothing и очистка не выполняется
Worksheets(«Sheet1»).Activate

MsgBox «Тип объекта » & TypeName(Selection)

Высвечивает тип предварительно выделенного на листе Sheet1 объекта

Понравилась статья? Поделить с друзьями:
  • Vba sql запрос к таблице excel
  • Vba sql запрос к листу excel
  • Vba set range in excel
  • Vba select table in word
  • Vba scripting for excel