MS Excel VBA Interview Questions and Answers with Examples
MS Excel VBA Interview Questions and Answers explained with Example macros. Here are the list of most frequently asked basic MS Excel VBA interview questions. All the questions are answered and explained with simple examples. These questions will help you to answer basic questions to deal with MS Excel VBA Programming/Development.
Application –> Workbooks –> Worksheets –> Range / Chart
Step 1: Go To Developer tab from the main ribbon of Excel window.
Step 2: Click on ‘Stop Recording’ command button to stop from the recording macro.
Step 1: Go To Developer tab from the main ribbon of Excel window.
Step 2: Click on the Macros command button to see the available macros in the active workbook.
Step 3: Once you click on the Macros command button, Macro dialog box will appear on the screen.
Step 4: Select macro name which you want to delete macro and then click on ‘Delete’ command button.
Step 5: Now, It will show the confirmation dialog box. Click on Ok to delete the macro.
To get Workbook_Open() Event in Excel, please find the following steps.
1. Go To VBA Editior.
2. Click on ‘ThisWorkbook’ from the Project Explorer.
3. Now, you can see two drop down lists in the right side.
4. Select ‘Workbook’ from the first drop down list and then choose ‘Open’ from the second drop down list.
5. Now, you can see the following code.
Private Sub Workbook_Open() ‘Your Statements….. End Sub
6. You can add the code in-between the above lines to run a macro.
7. Save and close the workbook
8. Now, reopen the workbook to test the macro.
Example:
Private Sub Workbook_Open() MsgBox “Workbook has Opened Successfully.”, vbInformation End Sub
In the above example, the macro will run automatically when we are opening workbook. Now, it will display message like “Workbook has Opened Successfully.”.
Or we can also define a procedure named Auto_Open() in any code module, this will execute while opening the macro file.
To get Workbook_Open() Event in Excel, please find the following steps.
1. Go To VBA Editior.
2. Click on ‘ThisWorkbook’ from the Project Explorer.
3. Now, you can see two drop down lists in the right side of the VBA Editor window.
4. Select ‘Workbook’ from the first drop down list and then choose ‘Open’ from the second drop down list.
5. Now, you can see the following code.
Private Sub Workbook_Open() ‘Your Statements….. End Sub
6. You can add the code in-between the above lines to run a macro.
7. Save and close the workbook
8. Now, reopen the workbook to test the macro.
Example:
Private Sub Workbook_Open() ‘ Here “MyForm” is the UserForm name. MyForm.Show End Sub
In the above example, the macro will show the UserForm(Named ‘MyForm’) automatically when we open Workbook.
Note: Before running above macro add UserForm and then assign the name of the UserForm to ‘MyForm’.
ByVal:
Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code.
ByRef:
Specifies that an argument is passed in such a way that the called procedure can change the value of a variable underlying the argument in the calling code.
Note: Default value is ByRef. It is good practice to include the ByRef declaration if you are going to change the value of the parameter.
For…. Next loop, Do While…. Loop, Do until Loop, Do….Loop Until..,Do While Not…Loop, While…. Wend loop
Add UserForm:
Step 1: Go To Insert menu in the VBA Editor window.
Step 2: Click on ‘UserForm to add to the Project. Now you can see added UserForm in the Project Explorer. Default UserForm name will be ‘UserForm1’. You can change the UserForm name with using properties
Add Module:
Step 1: Go To Insert menu in the VBA Editor window.
Step 2: Click on ‘Module’ to add to the Project. Now you can see added Module in the Project Explorer. Default module name will be ‘Module1’. You can change the module name with using properties.
Add Class Module:
Step 1: Go To Insert menu in the VBA Editor window.
Step 2: Click on ‘Class Module’ to add to the Project. Now you can see added Class Module in the Project Explorer. Default Class module name will be ‘Class1’. You can change the class module name with using properties.
Create object for Workbook:
Sub Create_Object_Workbook() Dim Wb As Workbook Set Wb = ActiveWorkbook MsgBox Wb.Sheets(1).Name End Sub
Explanation: In the above example, I have created and assigned to Active Workbook to ‘Wb’ objet. And then I have used it in the next statement(MsgBox Wb.Sheets(1).Name) to display first worksheet name.
We can create and define size of an array variable in the following way.
Dim ArrayName (IndexNumber) As Datatype
Example: Dim aValue(2) As Integer
In the above statement ‘aValue’ is an array name and ‘2’ indicates an array size.
‘Declare an array variable
Dim aValue (2) As Integer
aValue(0)=“first”
aValue(1)= “Second”
aValue(2)= “Third”
‘Or
Dim aValue () As Integer={“ first “,”Second”,”Third”}
Before using variable, we need to know how much space the variable will occupy in memory, because different variables occupy different amount of space in memory.
We can declare the variable in the following way.
Dim VariableName as Datatype
Example:
Dim iCnt as Integer
Where iCnt represents VariableName and Integer represents Datatype.
Byte, Boolean, Integer, Long, Single, Double, Currency, Decimal, Date, Object, String, Variant and User defined data types.
For more information please find the following link.
Button, Combo Box, Check Box, Spin Button, List Box, Option Button, Group Box, Label, Scroll Bar, etc,.
ActiveX Controls:
Command Button, Combo Box, Check Box, List Box, Text Box, Scroll Bar, Spin Button, Option Button, Label, Image, Toggle Button.
Step 1: Go to the Developer tab from the excel ribbon menu, go to Forms Control group.
Step 2: Click on Button from the Form Controls.
Step 3: Click the worksheet location where you want the button to appear.
Step 4: Drag the button in the sheet.
Step 5: Right click on the button, click on Assign Macro.
Step 6: Assign Macro Dialog box will appear now, click the name of the macro that you want to assign to the button. Click on OK.
Step 7: You can format the control by specifying control properties.
Step 8: Click on button to test. Now, your macro should run.
When we are working with variables, it is important to understand the Scope of a Variable. The Scope describes the accessibility or life time or visibility of a variable.
There are four levels of Scope:
• Procedure-Level Scope
• Module-Level Scope
• Project-Level Scope
• Global-Level Scope
For more information please find the following link.
Find last row in the worksheet:
Dim lastRow As Long
lastRow = ActiveSheet.Cells.SpecialCells(xlLastCell).Row
For more information please find the following link.
Find last column in the worksheet:
Dim lastColumn As Long
lastColumn = ActiveSheet.Cells.SpecialCells(xlLastCell).Column
For more information please find the following link.
We can fasten the execution of macros or VBA Procedures by following the below tips.
1. Declare the variables and avoid using ‘Variant’ Data Type.
2. Turn Off Screen Updating
3. Turn Off Automatic Calculations
4. Disable Events
5. Use With Statement
6. Use vbNullString instead of “”.
7. Release memory objects at the end of the procedure.
Here is the approach to enable or disable screen updating or screen flickering.
In order to stop the screen flickering, stop the screen updating at Staring of the procedure:
Application.ScreenUpdating = False
You have to set back screen updating as True Before ending of the procedure:
Application.ScreenUpdating = True
In order to stop triggers, disable the display alerts at Staring of the procedure:
Application.DisplayAlerts = False
You have to set enable display alerts before ending of the procedure:
Application.DisplayAlerts = True
1. On Error Resume Next
2. On Error Goto Err_Lbl
3. On Error Goto 0
You can find a specific file exist or not in the following two ways.
1. Using FileSystemObject:
Here is the example to check file exist or not using ‘FileSystemObject’.
Sub Check_File2() Dim FSO Dim sFileName As String sFileName = "C:/Test/Workbook.xls" Set FSO = CreateObject("Scripting.FileSystemObject") If Not FSO.FileExists(sFileName) Then MsgBox "File Does Not Exists." Else MsgBox "File Exists." End If End Sub
2. Using Dir Function:
Here is the example to check file exist or not using ‘Dir’ function.
Sub Check_File1() Dim sFileName As String sFileName = "C:/Test/Workbook.xls" If Dir(sFileName) <> "" Then MsgBox "File Exists." Else MsgBox "File Does Not Exists." End If End Sub
For more information please find the following link.
Sub Save_Workbook() Dim Wkb As Workbook Set Wkb = Workbooks.Add Wkb.Save End Sub
Please find the following link for more information on saving workbook using Excel VBA.
Sub SaveAs_Workbook() Dim Wkb As Workbook Set Wkb = Workbooks.Add ActiveWorkbook.SaveAs Filename:="C:Test.xlsm" End Sub
Please find the following link for more information on changeing the existing file name.
Sub sbDelete_File() Dim FSO Dim sFile As String sFile = "C:Test.xlsm" 'Set Object Set FSO = CreateObject("Scripting.FileSystemObject") 'Check File Exists or Not If FSO.FileExists(sFile) Then FSO.DeleteFile sFile, True MsgBox "Deleted The File Successfully", vbInformation, "Done!" Else MsgBox "Specified File Not Found", vbInformation, "Not Found!" End If End Sub
Note: Before deleting file from the specified location, we have to check whether file is exists or not in the specified location. In the above example we are using statement:’ FSO.FileExists(sFile)’ to check for the file.
Please find the following link for more information on deleting a file in a specified location.
Sub Copy_File() Dim FSO Dim sFileName As String Dim dFileName As String sFileName = "D:Test.xlsx" 'Source File Location Name dFileName = "E:Test.xlsx" 'Destination File Location Name Set FSO = CreateObject("Scripting.FileSystemObject") FSO.CopyFile sFileName, sFileName, True End Sub
Please find the following link for more information on copying a file from one location to another location.
Sub Move_File() Dim sFileName As String Dim dFileName As String sFileName = "D:Test.xlsx" 'Source File Location Name dFileName = "E:Test.xlsx" 'Destination File Location Name Name sFileName As sFileName End Sub
Xls,xlsx,xlsm,xla,xlam, etc.,
Sub Delete_EntireRow() Rows(5).EntireRow.Delete ‘ 5th row ‘or Rows(“1:5”).EntireRow.Delete ‘ first 5 rows End Sub
Please find the following link for more information on deleting rows in a worksheet
Sub Delete_EntireRow() Columna(“E”).EntireColumn.Delete ‘ 5th column Columna(“A:E”).EntireColumn.Delete ‘ first 5 columns End Sub
Please find the following link for more information on deleting columns in a Worksheet.
Sub Cell_Color() 'Using Cell Object Cells(3, 2).Interior.ColorIndex = 5 ' 5 indicates Blue Color End Sub
Please find the following link for more information on changing the cell color.
Sub Cell_Color() 'Using Range Object Range("A1:B5").Interior.ColorIndex = 5 ' 5 indicates Blue Color End Sub
Please find the following link for more information on changing the range color.
Hide Row(S):
Sub Hide_Row() Rows("5").EntireRow.Hidden = True 'Hides 5th Row(Single Row) Rows("1:5").EntireRow.Hidden = True 'Hides 1 to 5 Rows(Multiple Rows) End Sub
UnHide_Row(S):
Sub UnHide_Row() Rows("5").EntireRow.Hidden = False 'UnHide 5th Row(Single Row) Rows("1:5").EntireRow.Hidden = False 'UnHides 1 to 5 Rows(Multiple Rows) End Sub
Please find the following link for more information on hide or unhide rows.
Hide column (S):
Sub Hide_ Column () Rows("5").EntireColumn.Hidden = True 'Hides 5th Row(Single Row) Rows("1:5"). EntireColumn.Hidden = True 'Hides 1 to 5 Rows(Multiple Rows) End Sub
UnHide_ Column (S):
Sub UnHide_ Column () Rows("5"). EntireColumn.Hidden = False 'UnHide 5th Column (Single Column) Rows("1:5"). EntireColumn.Hidden = False 'UnHides 1 to 5 Columns(Multiple Columns) End Sub
Please find the following link for more information on hide or unhide columns.
Hide Sheet:
Sub Hide_Sheet() Sheets("Sheet1").Visible = True 'or Sheets("Sheet1").Visible = 2 'to very hide the worksheet End Sub
UnHide Sheet:
Sub UnHide_Sheet() Sheets("Sheet1").Visible = False End Sub
Please find the following link for more information on hide
Sub Open_Workbook() Workbooks.Open "D:Test.xlsx" End Sub
In the above example we are using ‘open’ method of workbook object to open workbook.
Please find the following link for more information on opening workbook.
Sub Close_Workbook() Dim Wkb As Workbook Set Wkb = Workbooks.Open("D:Test.xlsx") Wkb.Close savechanges:=True End Sub
In the above example we are using ‘close’ method of workbook object to close workbook.
Please find the following link for more information on closing workbook.
VB5: VB6 is a Visual programming language developed to help the users to easily develop the Windows Applications.
VBA: VBA is Visual Basic Programming for developing MS Office Applications. It’s available in all MS Office Tools, such as MS Excel, MS Access, MS PowerPoint and MS Word.
VB Script: Visual Basic Programming for Web Browser (Microsoft Internet Explorer). You can write the VBScript in html pages to program the different objects in Web Pages.
Offset Syntax:
OFFSET(reference, rows, cols, [Height], [Width])
In the above example Height and Width parameters are optional.
Please find the following link for more information on Offset.
Protect Sheet:
Sub Protect_Sheet() Sheets("Sheet1").Protect "YourPassword", True, True End Sub
In the above example we are protecting the worksheet by using ‘Protect’ method of Worksheet object.
UnProtect Sheet:
Sub UnProtect_Sheet() Sheets("Sheet1").UnProtect "YourPassword” End Sub
In the above example we are unprotecting the worksheet by using ‘UnProtect’ method of Worksheet object.
Please find the following link for more information on unprotecting worksheet.
Sub Find_LastRow_In_Worksheet() Dim lastRow As Long lastRow = Sheets("Sheet1").Cells.SpecialCells(xlLastCell).Row End Sub
Please find the following link for more information on finding last row in worksheet.
Sub Find_LastColumn_In_Worksheet() Dim lastCol As Long lastCol = Sheets("Sheet1").Cells.SpecialCells(xlLastCell).Column End Sub
Please find the following link for more information on finding last column in worksheet.
Here is the difference between Function and Subroutine.
Function:
Function will perform calculations based on specified conditions and then return a single value as a result. You can use function anywhere in the procedure and you can use number of times based on the requirement. You can use ‘Exit Function’ or ‘Return’ from immediate exit from a function procedure. Please find the following function statements.
Function Function_Name() Statements… End Function
Subroutine:
Subroutine cannot return any value and it will perform set of actions. We can declare any number of procedures or functions in a module. Procedures or functions can be called in another procedure procedure. You can use ‘Exit Sub’ from immediate exit from a Subroutine or procedure. Please find the following subroutine statements.
Sub Procedure_Name() Statements… End Sub
Use function procedure to return any value, Otherwise use a Sub procedure.
i) Create a class with the properties you require to return and then return the object of the class from the function.
ii) Using ByRef for the values.
iii) Return an array of the values
For Example, you might have entered some data at Range A1:D10 and then Range A20:D30.
Current Range of A1 (or any range in A1:D10) will be Range A1:D10. Similarlly current range of A20 .. or D30 will be A20:D30.
And the used range of the worksheet will be A1:D30.
Sub CurrentRange() MsgBox Range("A1").CurrentRegion.Address End Sub
One worksheet can have one or more current regions, and only one used range. So, used range will be collection of current regions.
Current region will be used to change the formats or calculations to particular block of range (region). And used range will be used to deal with the entire used range in the worksheet.
Current region will connected with at least on data cell (non empty cell). And the used ranges will consider if any range or cell is used once and even if the cell is blank.
You can used the below procedure to find the used range in a worksheet.
Sub UsedRange() MsgBox ActiveSheet.UsedRange.Address End Sub
As explained above, once you use any range it will be considered as used cell even after deleting the content in the cell. To get the used range with the data, please refer our examples on finding actual used range in the worksheet.
Example:
Sub Range_Clear() Range("A1:B5").Clear End Sub
Example:
Sub Range_ClearFormates() Range("A1:B5").ClearFormates End Sub
Example:
Sub Range_ClearHyperlinks() Range("A1:B5").ClearHyperlinks End Sub
Example:
Sub Range_ClearContents() Range("A1:B5").ClearContents End Sub
Option Explicit makes the declaration of Variables Mandatory. Option Base is used at module level to declare the default lower bound for array subscripts. Default array lower bound value is 0. If the default value is 0, then the Option Base statement is not required. If used, the statement must appear in a module before any procedures. Option Base can appear only once in a module and must precede array declarations that include dimensions.
Example: Option Base 1 will make the array lower bound as 1 instead of 0.
Used at module level to declare the default lower bound for array subscripts.
Syntax: Option Base {1} Or Option Base {1}
More VBA Interview Questions & Answers:
Here is the link for more VBA Interview Questions and Answers. These are explained for examples.
100+ VBA Interview Questions