Why we are here To learn something new which will make our life easy and efficient at workplace What is VBA • Full Form: • Visual Basic for Applications • VBA is Microsoft's common application programming (macro) language for: • • • • • Word Excel Access Powerpoint Many more What does VBA do? • Write Macros to Automate • When to start automating Labor-Intensive (Lot of manual efforts) Repetitive or Routine Tasks The Developer tab, which does not appear by default, contains useful commands for VBA users About Macro Security • Macros are so powerful that they can do serious damage to your computer • Was created to help prevent macro-related problems About Macro Security • With this setting if you open the workbook, excel displays a security warning above the formula bar • Click enable content and the macros will be enabled About Macro Security If the Visual Basic Editor window is open when you open a workbook that contains macros, Excel does not display the Security Warning above the Formula bar. Rather, it displays a dialog box with two buttons: Enable Macros and Disable Macros Saving Workbooks That Contain Macros Extension of Visual Basic: XLSM Excel warns you if your workbook contains macros and you attempt to save it in a nonmacro file format Types of VBA Macros Nickname of Macro: Procedure Two Types of Macro: Sub and Function A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements Go to excel - It will help in opening the window wherein you can write the macro code Alt + F11 Go to excel To run the macro at one go F5 Go to excel To run macro step by step F8 Creating VBA Macros Concepts – Objects Such as Worksheet, Workbook, Range, Cell, Chart, Name, etc. Worksheets(1) is an Object Referring to the First Sheet Range("A1:B15") is an Object Referring to a Range Cells(1,1) or Range(“A1”) is an Object Referring to Range “A1” Workbook Objects Workbook Objects The Workbook object is a member of the Workbooks collection and contains all the Workbook objects currently open in Microsoft Excel 'Ex 1 : To close Workbooks Workbooks.Close 'Ex 2 : To Add an Empty Work Book Workbooks.Add 'Ex 3: To Open a Workbook Workbooks.Open FileName:="Test.xls", ReadOnly:=True 'Ex : 4 - To Activate WorkBooks Workbooks("Test.xls").Worksheets("Sheet1").Activate Writing the data to first Cell of the Worksheet Workbook Objects The Workbook object is a member of the Workbooks collection and contains all the Workbook objects currently open in Microsoft Excel Sub US() Cells(1, 1)="Hello World" End Sub ‘Here the first value (1) is Row Value and the second one (1) is column value ‘Cells(1, 1) means first row first column Writing the data from first Cell of the worksheet Workbook Objects The Workbook object is a member of the Workbooks collection and contains all the Workbook objects currently open in Microsoft Excel Sub US() Range(“A2”)="Hello World" End Sub (‘Here you have to specify the Cell Name which you want to read – A is the Column and 2 is the Row) Worksheet Objects Worksheet Objects The Worksheet object is a member of the Worksheets collection and contains all the Worksheet objects in a workbook 'Ex 1 : To make it Invisible Worksheets(1).Visible = False 'Ex 2 : To protect an WorkSheet Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True Sub gaurav() Cells(2, 3).Select Selection.Font.Bold = True Selection.Font.Italic = True End Sub Range Objects Range Objects Range Objects represent a cell, a row, a column, or a selection of cells containing one or more continuous blocks of cells 'Ex 1 : To Put a value in the cell A5 Worksheets("Sheet1").Range("A5").Value = "5235" 'Ex 2 : To put a value in range of Cells Worksheets("Sheet1").Range("A1:A4").Value = 5 Final Example Sub juhi() Cells(2, 3) = "Hello life" Range("A1") = "Hello life" Cells(2, 3).Select Selection.Font.Bold = True Cells(2, 3).Select Selection.Font.Italic = True End Sub Displaying the Developer tab 1. Choose Office ➪ Excel Options. 2. In the Excel Options dialog box, select Personalize. 3. Place a check mark next to Show Developer tab in the Ribbon. 4. Click OK to return to Excel. Difference Between Cell and Range Cells usually reference a single cell at a time. Cells(Parameter1, Parameter2) Eg: Cells (Row no., Column no.) Cells (2,3) C2 Cells (3,4) D3 Range can refer a group of cells at once: Range(“Column row number”) Range(“A5”) More Examples with Range Sub juhi() Range("A1") = "Hello life" Range("A1").Select Selection.Font.Bold = True Selection.Font.Italic = True End Sub Example of Basic Logical Operator Addition Subtraction Average Multiplication Sub juhi() Range("A7").Formula = "=Sum(D17:E17)" Range("A4").Formula = "=D17-E17" Range("A1").Formula = "=average(A4:B7)" Range("A10").Formula = "=A5*A7" End Sub Example to get the current date and time Sub TimeStamp() ‘ ‘ TimeStamp Macro ‘ Keyboard Shortcut: Ctrl+Shift+T ‘ ActiveCell.FormulaR1C1 = “=NOW()” Or Activecell.formula = “=NOW()” Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, _ Operation:= xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False End Sub Sub juhi() ActiveCell.FormulaR1C1 = "=NOW()" Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False End Sub Explanation • • • • • • The procedure has four statements. First statement inserts NOW() formula into the active cell. Second statement copies the cell. Third statement, which is displayed on three lines (the underscore character means that the statement continues on the next line), pastes the Clipboard contents (as a value) to the current selection. The fourth statement cancels the moving border around the selected range. Note: You may notice that the macro recorded some actions that you didn’t take. For example, it specified several options for the PasteSpecial operation. Recording actions that you don’t specifically make is just a byproduct of the method that Excel uses to translate actions into code. For Loop For NEXT Loops You can use a For-Next loop to execute one or more statements a number of times. For-Next loop: Sub SumSquared() Total = 0 For Num = 1 To 10 Total = Total + (Num ^ 2) Next Num MsgBox Total End Sub This example has one statement between the For statement and the Next statement. This single statement is executed 10 times. The variable Num takes on successive values of 1, 2, 3, and so on, up to 10. The variable Total stores the sum of Num squared, added to the previous value of Total. The result is a value that represents the sum of the first 10 integers squared. This result is displayed in a message box. Sub SumSquared() Total = 0 For Num = 1 To 10 Total = Total + Num Next Num MsgBox Total End Sub Single Loop with Cells You can use a single loop to loop through a one-dimensional range of cells Sub juhi() For A = 1 To 6 Cells(A, 1).Value = 100 Next A End Sub Double Loop You can use a double loop to loop through a two-dimensional range of cells. Sub juhi() For i = 1 To 6 For j = 1 To 2 Cells(i, j).Value = 100 Next j Next i End Sub Do While Loop A Do…While loop is used when we want to repeat a set of statements as long as the condition is true. Sub juhi() i = 1 Do While i < 6 Cells(i, 1).Value = 20 i = i + 1 Loop End Sub Example of Msgbox The MsgBox is a dialog box in Excel VBA you can use to inform the users of your program. 1. A simple message. MsgBox "This is fun" Result when you click the command button on the sheet: More Examples A little more advanced message. First, enter a number into cell A1. MsgBox "Entered value is " & Range("A1").Value Result when you click the command button on the sheet: Recording VBA macros Excel’s macro recorder translates your actions into VBA code. To start the macro recorder, choose Developer ➪ Record Macro To begin recording your actions, click OK. When you finish recording the macro, choose Developer ➪ Code ➪ Stop Recording (or click the Stop Recording button in the status bar) Example The MyName procedure was generated by Excel’s macro recorder The macro recorded is a Sub procedure that is named MyName. The statements tell Excel what to do when the macro is executed ActiveCell.FormulaR1C1 = “John Walkenbach”: Statement causes the name to be inserted into the active cell. The FormulaR1C1 part is a property Example of a code When this code is executed, VBA inserts the following: • Current date into the active cell • Formats it • Makes the cell bold • Adjusts the column width