Top Banner

of 34

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 5/21/2018 Excel Macro(VBA)

    1/34

    Create a MacroWith Excel VBA you can automate tasks in Excel by writing so called macros. In this chapter, learn how to create asimple macro which will be executed after clicking on a command button. First, turn on the Developer tab.

    Developer TabTo turn on the Developter tab, execute the following steps.

    1. Right click anywhere on the ribbon, and then click Customize the Ribbon.

    2. Under Customize the Ribbon, on the right side of the dialog box, select Main tabs (if necessary).

    3. Check the Developer check box.

  • 5/21/2018 Excel Macro(VBA)

    2/34

    4. Click OK.

    5. You can find the Developer tab next to the View tab.

    Command ButtonTo place a command button on your worksheet, execute the following steps.

    1. On theDeveloper tab,click Insert.

    http://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tab
  • 5/21/2018 Excel Macro(VBA)

    3/34

    2. In the ActiveX Controls group, click Command Button.

    3. Drag a command button on your worksheet.

    Assign a MacroTo assign a macro (one or more code lines) to the command button, execute the following steps.

    1. Right click CommandButton1 (make sure Design Mode is selected).

    2. Click View Code.

  • 5/21/2018 Excel Macro(VBA)

    4/34

    The Visual Basic Editor appears.

    3. Place your cursor between Private Sub CommandButton1_Click() and End Sub.

    4. Add the code line shown below.

  • 5/21/2018 Excel Macro(VBA)

    5/34

    Note: the window on the left with the names Sheet1, Sheet2 and Sheet3 is called the Project Explorer. If the Project

    Explorer is not visible, click View, Project Explorer. To add the Code window for the first sheet, click Sheet1 (Sheet1).

    5. Close the Visual Basic Editor.

    6. Click the command button on the sheet (make sure Design Mode is deselected).

    Result:

    Congratulations. You've just created a macro in Excel!

    Visual Basic EditorTo open the Visual Basic Editor, on theDeveloper tab,click Visual Basic.

    http://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tab
  • 5/21/2018 Excel Macro(VBA)

    6/34

    The Visual Basic Editor appears.

    MsgBox

    The MsgBox is a dialog box in Excel VBA you can use to inform the users of your program. Place a command

    buttonon your worksheet and add the following code lines:

    1. A simple message.

    MsgBox "This is fun"

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    7/34

    Result when you click the command button on the sheet:

    2. 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:

    Note: we used the & operator to concatenate (join) two strings. Although Range("A1").value is not a string, it works

    here.

    3. To start a new line in a message, use vbNewLine.

    MsgBox "Line 1" & vbNewLine & "Line 2"

    Result when you click the command button on the sheet:

  • 5/21/2018 Excel Macro(VBA)

    8/34

    Workbook and WorksheetObject

    Learn more about the Workbook and Worksheet object in Excel VBA.

    Object Hierarchy

    In Excel VBA, an object can contain another object, and that object can contain another object, etc. In other words,

    Excel VBA programming involves working with an object hierarchy. This probably sounds quite confusing, but we will

    make it clear.

    The mother of all objects is Excel itself. We call it the Application object. The application object contains other objects.

    For example, the Workbook object (Excel file). This can be any workbook you have created. The Workbook object

    contains other objects, such as the Worksheet object. The Worksheet object contains other objects, such as the

    Range object.

    TheCreate a Macrochapter illustrates how to run code by clicking on a command button. We used the following

    code line:

    Range("A1").Value = "Hello"

    but what we really meant was:

    Application.Workbooks("create-a-macro").Worksheets(1).Range("A1").Value = "Hello"

    Note: the objects are connected with a dot. Fortunately, we do not have to add a code line this way. That is because

    we placed our command button in create-a-macro.xls, on the first worksheet. Be aware that if you want to change

    different things on different worksheets to include the Worksheet object. Read on.

    CollectionsYou may have noticed that Workbooks and Worksheets are both plural. That is because they are collections. The

    Workbooks collection contains all the Workbook objects that are currently open. The Worksheets collection contains

    all the Worksheet objects in a workbook.

    http://www.excel-easy.com/vba/create-a-macro.htmlhttp://www.excel-easy.com/vba/create-a-macro.htmlhttp://www.excel-easy.com/vba/create-a-macro.htmlhttp://www.excel-easy.com/vba/create-a-macro.html
  • 5/21/2018 Excel Macro(VBA)

    9/34

    You can refer to a member of the collection, for example, a single Worksheet object, in three ways.

    1. Using the worksheet name.

    Worksheets("Sales").Range("A1").Value = "Hello"

    2. Using the index number (1 is the first worksheet starting from the left).

    Worksheets(1).Range("A1").Value = "Hello"

    3. Using the CodeName.

    Sheet1.Range("A1").Value = "Hello"

    To see the CodeName of a worksheet, open theVisual Basic Editor. In the Project Explorer, the first name is the

    CodeName. The second name is the worksheet name (Sales).

    Note: the CodeName remains the same if you change the worksheet name or the order of your worksheets so this is

    the safest way to reference a worksheet. Click View, Properties Window to change the CodeName of a worksheet.

    There is one disadvantage, you cannot use the CodeName if you reference a worksheet in a different workbook.

    Properties and MethodsNow let's take a look at some properties and methods of the Workbooks and Worksheets collection. Properties are

    something which an collection has (they describe the collection), while methods do something (they perform an action

    with an collection).

    Place acommand buttonon your worksheet and add the code lines:

    http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor
  • 5/21/2018 Excel Macro(VBA)

    10/34

    1. The Add method of the Workbooks collection creates a new workbook.

    Workbooks.Add

    Note: the Add method of the Worksheets collection creates a new worksheet.

    2. The Count property of the Worksheets collection counts the number of worksheets in a workbook.

    MsgBox Worksheets.Count

    Result when you click the command button on the sheet:

    Note: the Count property of the Workbooks collection counts the number of active workbooks.

    Range ObjectThe Range object, which is the representation of a cell (or cells) on your worksheet, is the most important object

    of Excel VBA. This chapter gives an overview of the properties and methods of the Range object. Properties aresomething which an object has (they describe the object), while methods do something (they perform an action withan object).

    Range ExamplesPlace acommand buttonon your worksheet and add the following code line:

    Range("B3").Value = 2

    Result when you click the command button on the sheet:

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    11/34

    Code:

    Range("A1:A4").Value = 5

    Result:

    Code:

    Range("A1:A2,B3:C4").Value = 10

    Result:

    CellsInstead of Range, you can also use Cells. Using Cells is particularly useful when you want toloopthrough ranges.

    Code:

    Cells(3, 2).Value = 2

    Result:

    Explanation: Excel VBA enters the value 2 into the cell at the intersection of row 3 and column 2.

    http://www.excel-easy.com/vba/loop.htmlhttp://www.excel-easy.com/vba/loop.htmlhttp://www.excel-easy.com/vba/loop.htmlhttp://www.excel-easy.com/vba/loop.html
  • 5/21/2018 Excel Macro(VBA)

    12/34

    Code:

    Range(Cells(1, 1), Cells(4, 1)).Value = 5

    Result:

    Declare a Range ObjectYou can declare a Range object by using the keywords Dim and Set.

    Code:

    Dimexample AsRange

    Setexample = Range("A1:C4")

    example.Value = 8

    Result:

    SelectAn important method of the Range object is the Select method. The Select method simply selects a range.

    Code:

    Dimexample AsRange

    Setexample = Range("A1:C4")

    example.Select

    Result:

  • 5/21/2018 Excel Macro(VBA)

    13/34

    RowsThe Rows property gives access to a specific row of a range.

    Code:

    Dimexample AsRange

    Setexample = Range("A1:C4")

    example.Rows(3).Select

    Result:

    Note: border for illustration only.

    ColumnsThe Columns property gives access to a specific column of a range.

    Code:

    Dimexample AsRange

    Setexample = Range("A1:C4")

    example.Columns(2).Select

    Result:

  • 5/21/2018 Excel Macro(VBA)

    14/34

    Note: border for illustration only.

    Copy/PasteThe Copy and Paste method are used to copy a range and to paste it somewhere else on the worksheet.

    Code:

    Range("A1:A2").SelectSelection.Copy

    Range("C3").Select

    ActiveSheet.Paste

    Result:

    Although this is allowed in Excel VBA, it is much better to use the code line below which does exactly the same.

    Range("C3:C4").Value = Range("A1:A2").Value

    ClearTo clear the content of an Excel range, you can use the ClearContents method.

    Range("A1").ClearContents

    or simply use:

    Range("A1").Value = ""

  • 5/21/2018 Excel Macro(VBA)

    15/34

    Note: use the Clear method to clear the content and format of a range. Use the ClearFormats method to clear the

    format only.

    Count

    With the Count property, you can count the number of cells, rows and columns of a range.

    Note: border for illustration only.

    Code:

    Dimexample AsRange

    Setexample = Range("A1:C4")

    MsgBox example.Count

    Result:

    Code:

    Dimexample AsRange

    Setexample = Range("A1:C4")

    MsgBox example.Rows.Count

    Result:

  • 5/21/2018 Excel Macro(VBA)

    16/34

    Note: in a similar way, you can count the number of columns of a range.

    VariablesInteger | String | Double | Boolean

    This chapter teaches you how to declare, initialize and display a variable in Excel VBA. Letting Excel VBA know you

    are using a variable is called declaring a variable. Initializing simply means assigning a beginning (initial) value to a

    variable.

    Place acommand buttonon your worksheet and add the code lines below. To execute the code lines, click the

    command button on the sheet.

    IntegerInteger variables are used to store whole numbers.

    Dimx AsInteger

    x = 6

    Range("A1").Value = x

    Result:

    http://www.excel-easy.com/vba/variables.html#integerhttp://www.excel-easy.com/vba/variables.html#integerhttp://www.excel-easy.com/vba/variables.html#stringhttp://www.excel-easy.com/vba/variables.html#stringhttp://www.excel-easy.com/vba/variables.html#doublehttp://www.excel-easy.com/vba/variables.html#doublehttp://www.excel-easy.com/vba/variables.html#booleanhttp://www.excel-easy.com/vba/variables.html#booleanhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/variables.html#booleanhttp://www.excel-easy.com/vba/variables.html#doublehttp://www.excel-easy.com/vba/variables.html#stringhttp://www.excel-easy.com/vba/variables.html#integer
  • 5/21/2018 Excel Macro(VBA)

    17/34

    Explanation: the first code line declares a variable with name x of type Integer. Next, we initialize x with value 6.

    Finally, we write the value of x to cell A1.

    String

    String variables are used to store text.

    Code:

    Dimbook AsString

    book = "bible"

    Range("A1").Value = book

    Result:

    Explanation: the first code line declares a variable with name book of type String. Next, we initialize book with the text

    bible. Always use apostrophes to initialize String variables. Finally, we write the text of the variable book to cell A1.

    DoubleA variable of type Double is more accurate than a variable of type Integer and can also store numbers after thecomma.

    Code:

    Dimx AsInteger

    x = 5.5

    MsgBox "value is " & x

    Result:

  • 5/21/2018 Excel Macro(VBA)

    18/34

    But that is not the right value! We initialized the variable with value 5.5 and we get the value 6. What we need is a

    variable of type Double.

    Code:

    Dimx AsDouble

    x = 5.5

    MsgBox "value is " & x

    Result:

    Note: Long variables have even larger capacity. Always use variables of the right type. As a result, errors are easier

    to find and your code will run faster.

    BooleanUse a Boolean variable to hold the value True or False.

    Code:

    Dimcontinue AsBoolean

    continue = True

    Ifcontinue = TrueThenMsgBox "Boolean variables are cool"

    Result:

  • 5/21/2018 Excel Macro(VBA)

    19/34

    Explanation: the first code line declares a variable with name continue of type Boolean. Next, we initialize continue

    with the value True. Finally, we use the Boolean variable to only display a MsgBox if the variable holds the value

    True.

    If Then StatementIf Then Statement | Else Statement

    Use the If Then statement in Excel VBA to execute code lines if a specific condition is met.

    If Then Statement

    Place acommand buttonon your worksheet and add the following code lines:

    Dimscore AsInteger, result AsString

    score = Range("A1").Value

    Ifscore >= 60 Thenresult = "pass"

    Range("B1").Value = result

    Explanation: if score is greater than or equal to 60, Excel VBA returns pass.

    Result when you click the command button on the sheet:

    http://www.excel-easy.com/vba/if-then-statement.html#if-then-statementhttp://www.excel-easy.com/vba/if-then-statement.html#if-then-statementhttp://www.excel-easy.com/vba/if-then-statement.html#else-statementhttp://www.excel-easy.com/vba/if-then-statement.html#else-statementhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/if-then-statement.html#else-statementhttp://www.excel-easy.com/vba/if-then-statement.html#if-then-statement
  • 5/21/2018 Excel Macro(VBA)

    20/34

    Note: if score is less than 60, Excel VBA places the value of the empty variable result into cell B1.

    Else StatementPlace acommand buttonon your worksheet and add the following code lines:

    Ads by BlockAndSurfAd Options

    Dimscore AsInteger, result AsString

    score = Range("A1").Value

    Ifscore >= 60 Then

    result = "pass"

    Else

    result = "fail"

    EndIf

    Range("B1").Value = result

    Explanation: if score is greater than or equal to 60, Excel VBA returns pass, else Excel VBA returns fail.

    Result when you click the command button on the sheet:

    Note: only if you have one code line after Then and no Else statement, it is allowed to place a code line directly after

    Then and to omit (leave out) End If (first example). Otherwise start a new line after the words Then and Else and end

    with End If (second example).

    LoopSingle Loop | Double Loop | Triple Loop | Do While LoopLooping is one of the most powerful programming techniques. A loop in Excel VBA enables you to loop through a

    range of cells with just a few codes lines.

    Single Loop

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://nep.makemace.net/sd/apps/adinfo-1.0/index.html?bj1CbG9ja0FuZFN1cmYmaD1uZXAubWFrZW1hY2UubmV0JmM9Z3JlZW4mbz13c2FyJmQ9JnQ9MTsyOzM7NDs1OzY7Nzs4Ozk7MTA7MTE7MTI7MTM7MTQmYT0yMjIyJnM9MjA2NCZ3PXd3dy5leGNlbC1lYXN5LmNvbSZiPWJkMiZyZD0mcmk9http://nep.makemace.net/sd/apps/adinfo-1.0/index.html?bj1CbG9ja0FuZFN1cmYmaD1uZXAubWFrZW1hY2UubmV0JmM9Z3JlZW4mbz13c2FyJmQ9JnQ9MTsyOzM7NDs1OzY7Nzs4Ozk7MTA7MTE7MTI7MTM7MTQmYT0yMjIyJnM9MjA2NCZ3PXd3dy5leGNlbC1lYXN5LmNvbSZiPWJkMiZyZD0mcmk9http://www.excel-easy.com/vba/loop.html#single-loophttp://www.excel-easy.com/vba/loop.html#single-loophttp://www.excel-easy.com/vba/loop.html#double-loophttp://www.excel-easy.com/vba/loop.html#double-loophttp://www.excel-easy.com/vba/loop.html#triple-loophttp://www.excel-easy.com/vba/loop.html#triple-loophttp://www.excel-easy.com/vba/loop.html#do-while-loophttp://www.excel-easy.com/vba/loop.html#do-while-loophttp://www.excel-easy.com/vba/loop.html#do-while-loophttp://www.excel-easy.com/vba/loop.html#triple-loophttp://www.excel-easy.com/vba/loop.html#double-loophttp://www.excel-easy.com/vba/loop.html#single-loophttp://nep.makemace.net/sd/apps/adinfo-1.0/index.html?bj1CbG9ja0FuZFN1cmYmaD1uZXAubWFrZW1hY2UubmV0JmM9Z3JlZW4mbz13c2FyJmQ9JnQ9MTsyOzM7NDs1OzY7Nzs4Ozk7MTA7MTE7MTI7MTM7MTQmYT0yMjIyJnM9MjA2NCZ3PXd3dy5leGNlbC1lYXN5LmNvbSZiPWJkMiZyZD0mcmk9http://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    21/34

    You can use a single loop to loop through a one-dimensional range of cells.

    Place acommand buttonon your worksheet and add the following code lines:

    Dimi AsInteger

    Fori = 1 To6

    Cells(i, 1).Value = 100

    Nexti

    Result when you click the command button on the sheet:

    Explanation: The code lines between For and Next will be executed six times. For i = 1, Excel VBA enters the value

    100 into the cell at the intersection of row 1 and column 1. When Excel VBA reaches Next i, it increases i with 1 and

    jumps back to the For statement. For i = 2, Excel VBA enters the value 100 into the cell at the intersection of row 2

    and column 1, etc.

    Note: it is good practice to always indent (tab) the code between the words For and Next. This makes your code

    easier to read.

    Double LoopYou can use a double loop to loop through a two-dimensional range of cells.

    Place acommand buttonon your worksheet and add the following code lines:

    Dimi AsInteger, j AsInteger

    Fori = 1 To6

    Forj = 1 To2

    Cells(i, j).Value = 100

    Nextj

    Nexti

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    22/34

    Result when you click the command button on the sheet:

    Explanation: For i = 1 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 1 and column

    1. When Excel VBA reaches Next j, it increases j with 1 and jumps back to the For j statement. For i = 1 and j = 2,

    Excel VBA enters the value 100 into the cell at the intersection of row 1 and column 2. Next, Excel VBA ignores Next j

    because j only runs from 1 to 2. When Excel VBA reaches Next i, it increases i with 1 and jumps back to the For i

    statement. For i = 2 and j = 1, Excel VBA enters the value 100 into the cell at the intersection of row 2 and column 1,

    etc.

    Triple LoopYou can use a triple loop to loop through two-dimensional ranges on multiple Excel worksheets.

    Place acommand buttonon your worksheet and add the following code lines:

    Ads by BlockAndSurfAd Options

    Dimc AsInteger, i AsInteger, j AsInteger

    Forc = 1 To3

    Fori = 1 To6

    Forj = 1 To2

    Worksheets(c).Cells(i, j).Value = 100

    Nextj

    Nexti

    Nextc

    Explanation: The only change made compared to the code for the double loop is that we have added one moreloop

    and added Worksheets(c). in front of Cells to get the two-dimensional range on the first sheet for c = 1, the second

    sheet for c = 2 and the third sheet for c = 3. Download the Excel file to see this result.

    Do While LoopBesides the For Next loop, there are other loops in Excel VBA. For example, the Do While Loop. Code placed

    between Do While and Loop will be repeated as long as the part after Do While is true.

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://nep.makemace.net/sd/apps/adinfo-1.0/index.html?bj1CbG9ja0FuZFN1cmYmaD1uZXAubWFrZW1hY2UubmV0JmM9Z3JlZW4mbz13c2FyJmQ9JnQ9MTsyOzM7NDs1OzY7Nzs4Ozk7MTA7MTE7MTI7MTM7MTQmYT0yMjIyJnM9MjA2NCZ3PXd3dy5leGNlbC1lYXN5LmNvbSZiPWJkMiZyZD0mcmk9http://nep.makemace.net/sd/apps/adinfo-1.0/index.html?bj1CbG9ja0FuZFN1cmYmaD1uZXAubWFrZW1hY2UubmV0JmM9Z3JlZW4mbz13c2FyJmQ9JnQ9MTsyOzM7NDs1OzY7Nzs4Ozk7MTA7MTE7MTI7MTM7MTQmYT0yMjIyJnM9MjA2NCZ3PXd3dy5leGNlbC1lYXN5LmNvbSZiPWJkMiZyZD0mcmk9http://nep.makemace.net/sd/apps/adinfo-1.0/index.html?bj1CbG9ja0FuZFN1cmYmaD1uZXAubWFrZW1hY2UubmV0JmM9Z3JlZW4mbz13c2FyJmQ9JnQ9MTsyOzM7NDs1OzY7Nzs4Ozk7MTA7MTE7MTI7MTM7MTQmYT0yMjIyJnM9MjA2NCZ3PXd3dy5leGNlbC1lYXN5LmNvbSZiPWJkMiZyZD0mcmk9http://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    23/34

    1. Place acommand buttonon your worksheet and add the following code lines:

    Dimi AsInteger

    i = 1

    DoWhilei < 6Cells(i, 1).Value = 20

    i = i + 1

    Loop

    Result when you click the command button on the sheet:

    Explanation: as long as i is lower than 6, Excel VBA enters the value 20 into the cell at the intersection of row i and

    column 1 and increments i by 1. In Excel VBA (and in other programming languages), the symbol '=' means

    becomes. It does not mean equal. So i = i + 1 means i becomes i + 1. In other words: take the present value of i and

    add 1 to it. For example, if i = 1, i becomes 1 + 1 = 2. As a result, the value 20 will be placed into column A five times

    (not six because Excel VBA stops when i equals 6).

    2. Enter some numbers in column A.

    3. Place acommand buttonon your worksheet and add the following code lines:

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    24/34

    Dimi AsInteger

    i = 1

    DoWhileCells(i, 1).Value ""

    Cells(i, 2).Value = Cells(i, 1).Value + 10

    i = i + 1Loop

    Result when you click the command button on the sheet:

    Explanation: as long as Cells(i, 1).Value is not empty ( means not equal to), Excel VBA enters the value into the

    cell at the intersection of row i and column 2, that is 10 higher than the value in the cell at the intersection of row i and

    column 1. Excel VBA stops when i equals 7 because Cells(7, 1).Value is empty. This is a great way to loop through

    any number of rows on a worksheet.

    Macro Errors

    This chapter teaches you how to deal with MACRO ERRORS in EXCEL. First, let's create some errors.

    Place acommand buttonon your worksheet and add the following code lines:

    x = 2

    Range("A1").Valu = x

    1. Click the COMMAND BUTTON on the sheet.

    Result:

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    25/34

    2. Click OK.

    The variable x is not defined. Because we are using theOption Explicitstatement at the start of our code, we have to

    declare all our variables. Excel VBA has colored the x blue to indicate the error.

    3. In the Visual Basic Editor, click Reset to STOP the debugger.

    4. Correct the error by adding the following code line at the start of the code.

    Dimx AsInteger

    You may have heard of the technique called DEBUGGING before. With this technique you can step through your

    code.

    5. In the Visual Basic Editor, place your cursor before Private and press F8.

    The first line turns yellow.

    http://www.excel-easy.com/vba/examples/option-explicit.htmlhttp://www.excel-easy.com/vba/examples/option-explicit.htmlhttp://www.excel-easy.com/vba/examples/option-explicit.htmlhttp://www.excel-easy.com/vba/examples/option-explicit.html
  • 5/21/2018 Excel Macro(VBA)

    26/34

    6. Press F8 three MORE times.

    The following error appears.

  • 5/21/2018 Excel Macro(VBA)

    27/34

    The Range object has a property called Value. Value isn't spelled correctly here. Debugging is a great way to not only

    find errors, but also understand code better. OurDebuggingexample program shows you how to single step through

    your code and see the effect of each code line on your worksheet.

    String ManipulationJoin Strings | Left | Right | Mid | Len | Instr

    In this chapter you find the most important FUNCTIONS to manipulate strings in EXCEL VBA.

    Place acommand buttonon your worksheet and add the code lines below. To execute the code lines, click

    theCOMMAND BUTTON on the sheet.

    Join StringsWe use the & operator to concatenate (join) strings.

    Code:

    Dimtext1 AsString, text2 AsString

    text1 = "Hi"

    text2 = "Tim"

    MsgBox text1 & " " & text2

    Result:

    http://www.excel-easy.com/vba/examples/debugging.htmlhttp://www.excel-easy.com/vba/examples/debugging.htmlhttp://www.excel-easy.com/vba/examples/debugging.htmlhttp://www.excel-easy.com/vba/string-manipulation.html#join-stringshttp://www.excel-easy.com/vba/string-manipulation.html#join-stringshttp://www.excel-easy.com/vba/string-manipulation.html#lefthttp://www.excel-easy.com/vba/string-manipulation.html#lefthttp://www.excel-easy.com/vba/string-manipulation.html#righthttp://www.excel-easy.com/vba/string-manipulation.html#righthttp://www.excel-easy.com/vba/string-manipulation.html#midhttp://www.excel-easy.com/vba/string-manipulation.html#midhttp://www.excel-easy.com/vba/string-manipulation.html#lenhttp://www.excel-easy.com/vba/string-manipulation.html#lenhttp://www.excel-easy.com/vba/string-manipulation.html#instrhttp://www.excel-easy.com/vba/string-manipulation.html#instrhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/string-manipulation.html#instrhttp://www.excel-easy.com/vba/string-manipulation.html#lenhttp://www.excel-easy.com/vba/string-manipulation.html#midhttp://www.excel-easy.com/vba/string-manipulation.html#righthttp://www.excel-easy.com/vba/string-manipulation.html#lefthttp://www.excel-easy.com/vba/string-manipulation.html#join-stringshttp://www.excel-easy.com/vba/examples/debugging.html
  • 5/21/2018 Excel Macro(VBA)

    28/34

    Note: to insert a space, use " "

    LeftTo extract the leftmost characters from a string, use Left.

    Code:

    Dimtext AsString

    text = "example text"

    MsgBox Left(text, 4)

    Result:

    RightTo extract the rightmost characters from a string, use Right. We can also directly INSERT TEXT in a function.

    Code:

    MsgBox Right("example text", 2)

    Result:

  • 5/21/2018 Excel Macro(VBA)

    29/34

    MidTo extract a SUBSTRING, starting in the middle of a string, use Mid.

    Code:

    MsgBox Mid("example text", 9, 2)

    Result:

    Note: started at position 9 (t) with length 2. You can omit the third argument if you want to extract a substring starting

    in the middle of a string, until the end of the string.

    LenTo get the length of a string, use Len.

    Code:

    MsgBox Len("example text")

    Result:

  • 5/21/2018 Excel Macro(VBA)

    30/34

    Note: space (position 8) included!

    InstrTo find the position of a substring in a string, use INSTR.

    Code:

    MsgBox Instr("example text", "am")

    Result:

    Note: string "am" found at position 3.

    Date and TimeYear, Month, Day of a Date|DateAdd|Current Date and Time|Hour, Minute, Second|TimeValue

    Learn how to work with dates and times in

    Excel

    VBA.

    http://www.excel-easy.com/vba/date-time.html#year-month-day-datehttp://www.excel-easy.com/vba/date-time.html#year-month-day-datehttp://www.excel-easy.com/vba/date-time.html#dateaddhttp://www.excel-easy.com/vba/date-time.html#dateaddhttp://www.excel-easy.com/vba/date-time.html#dateaddhttp://www.excel-easy.com/vba/date-time.html#current-date-timehttp://www.excel-easy.com/vba/date-time.html#current-date-timehttp://www.excel-easy.com/vba/date-time.html#current-date-timehttp://www.excel-easy.com/vba/date-time.html#hour-minute-secondhttp://www.excel-easy.com/vba/date-time.html#hour-minute-secondhttp://www.excel-easy.com/vba/date-time.html#hour-minute-secondhttp://www.excel-easy.com/vba/date-time.html#timevaluehttp://www.excel-easy.com/vba/date-time.html#timevaluehttp://www.excel-easy.com/vba/date-time.html#timevaluehttp://www.excel-easy.com/vba/date-time.html#timevaluehttp://www.excel-easy.com/vba/date-time.html#hour-minute-secondhttp://www.excel-easy.com/vba/date-time.html#current-date-timehttp://www.excel-easy.com/vba/date-time.html#dateaddhttp://www.excel-easy.com/vba/date-time.html#year-month-day-date
  • 5/21/2018 Excel Macro(VBA)

    31/34

    Place acommand buttonon your worksheet and add the code lines below. To execute the code lines, click

    thecommand buttonon the sheet.

    Year, Month, Day of a Date

    The following macro gets the year of a date. To declare a date, use the Dim statement. To initialize a date, use the

    DateValue function.

    Code:

    DimexampleDate AsDate

    exampleDate = DateValue("Jun 19, 2010")

    MsgBox Year(exampleDate)

    Result:

    Note: Use Month and Day to get the month and day of a date.

    DateAddTo add a number of days to a date, use the DateAddfunction. The DateAdd function has three arguments. Fill in "d"

    for the first argument to add days. Fill in 3 for the second argument to add 3 days. The third argument represents the

    date to which the number of days will be added.

    Code:

    DimfirstDate AsDate, secondDate AsDate

    firstDate = DateValue("Jun 19, 2010")

    secondDate = DateAdd("d", 3, firstDate)

    MsgBox secondDate

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 5/21/2018 Excel Macro(VBA)

    32/34

    Result:

    Note: Change "d" to "m" to add a number of months to a date. Place your cursor on DateAdd in the Visual Basic

    Editor and click F1 for help on the other interval specifiers. Dates are in US Format. Months first, Days second. This

    type of format depends on your windowsregional settings.

    Current Date and TimeTo get the current date and time, use the Now function.

    Code:

    MsgBox Now

    Result:

    Hour, Minute, SecondThe get the hour of a time, use the Hour function.

    Code:

    MsgBox Hour(Now)

    Result:

  • 5/21/2018 Excel Macro(VBA)

    33/34

    Note: Use Minute and Second to get the minute and second of a time.

    TimeValueThe TimeValuefunction converts a string to a time serial number. The time's serial number is a number between 0

    and 1. For example, noon (halfway through the day) is represented as 0.5.

    Code:

    MsgBox TimeValue("9:20:01 am")

    Result:

    Now, to clearly see that Excel handles times internally as numbers between 0 and 1, add the following code lines:

    Dimy AsDouble

    y = TimeValue("09:20:01")

    MsgBox y

    Result:

  • 5/21/2018 Excel Macro(VBA)

    34/34