1 create a macro

Upload: keyur

Post on 01-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 1 Create a Macro

    1/44

    1 Create a Macro: With Excel VBA you can automate tasks in Excel by writing so called macros. n thischa!ter" learn how to create a sim!le macro.

    # MsgBox: $he MsgBox is a dialog box in Excel VBA you can use to in%orm the users o% your !rogram.

    & Workbook and Worksheet 'b(ect: )earn more about the Workbook and Worksheet ob(ect in Excel VBA.

    * +ange 'b(ect: $he +ange ob(ect" which is the re!resentation o% a cell ,or cells- on your worksheet" is themost im!ortant ob(ect o% Excel VBA.

    Variables: $his cha!ter teaches you how to declare" initiali/e and dis!lay a 0ariable in Excel VBA.

    % $hen 2tatement: 3se the % $hen statement in Excel VBA to execute code lines i% a s!eci%ic condition ismet.

    4 )oo!: )oo!ing is one o% the most !ower%ul !rogramming techni5ues. A loo! in Excel VBA enables you toloo! through a range o% cells with (ust a %ew codes lines.

    6 Macro Errors: $his cha!ter teaches you how to deal with macro errors in Excel.

    7 2tring Mani!ulation: n this cha!ter" you8ll %ind the most im!ortant %unctions to mani!ulate strings in ExcelVBA.

    19 ate and $ime: )earn how to work with dates and times in Excel VBA.

    11E0ents:E0ents are actions !er%ormed by users which trigger Excel VBA to execute code.

    1# Array: An array is a grou! o% 0ariables. n Excel VBA" you can re%er to a s!eci%ic 0ariable ,element- o%an array by using the array name and the index number.

    1& ;unction and 2ub: n Excel VBA" a %unction can return a 0alue while a sub cannot.

    1* A!!lication 'b(ect: $he mother o% all ob(ects is Excel itsel%. We call it the A!!lication ob(ect. $hea!!lication ob(ect gi0es access to a lot o% Excel related o!tions.

    1 Acti0e< Controls: )earn how to create Acti0e< controls such as command buttons" text boxes" list boxesetc.

    1 3ser%orm: $his cha!ter teaches you how to create an Excel VBA 3ser%orm.

    1 Create a Macro: With Excel VBA you can automate tasks in Excel by writingso called macros. n this cha!ter" learn how to create a sim!le macro.

    http://www.excel-easy.com/vba/create-a-macro.htmlhttp://www.excel-easy.com/vba/msgbox.htmlhttp://www.excel-easy.com/vba/workbook-worksheet-object.htmlhttp://www.excel-easy.com/vba/range-object.htmlhttp://www.excel-easy.com/vba/variables.htmlhttp://www.excel-easy.com/vba/if-then-statement.htmlhttp://www.excel-easy.com/vba/loop.htmlhttp://www.excel-easy.com/vba/macro-errors.htmlhttp://www.excel-easy.com/vba/string-manipulation.htmlhttp://www.excel-easy.com/vba/date-time.htmlhttp://www.excel-easy.com/vba/events.htmlhttp://www.excel-easy.com/vba/events.htmlhttp://www.excel-easy.com/vba/events.htmlhttp://www.excel-easy.com/vba/array.htmlhttp://www.excel-easy.com/vba/function-sub.htmlhttp://www.excel-easy.com/vba/application-object.htmlhttp://www.excel-easy.com/vba/activex-controls.htmlhttp://www.excel-easy.com/vba/userform.htmlhttp://www.excel-easy.com/vba/create-a-macro.htmlhttp://www.excel-easy.com/vba/create-a-macro.htmlhttp://www.excel-easy.com/vba/msgbox.htmlhttp://www.excel-easy.com/vba/workbook-worksheet-object.htmlhttp://www.excel-easy.com/vba/range-object.htmlhttp://www.excel-easy.com/vba/variables.htmlhttp://www.excel-easy.com/vba/if-then-statement.htmlhttp://www.excel-easy.com/vba/loop.htmlhttp://www.excel-easy.com/vba/macro-errors.htmlhttp://www.excel-easy.com/vba/string-manipulation.htmlhttp://www.excel-easy.com/vba/date-time.htmlhttp://www.excel-easy.com/vba/events.htmlhttp://www.excel-easy.com/vba/array.htmlhttp://www.excel-easy.com/vba/function-sub.htmlhttp://www.excel-easy.com/vba/application-object.htmlhttp://www.excel-easy.com/vba/activex-controls.htmlhttp://www.excel-easy.com/vba/userform.htmlhttp://www.excel-easy.com/vba/create-a-macro.html
  • 8/9/2019 1 Create a Macro

    2/44

    With Excel VBAyou can automate tasks in Excel by writing so called macros. n this cha!ter" learn how tocreate a sim!le macrowhich will be executed a%ter clicking on a command button. ;irst" turn on thee0elo!er tab.

    Developer Tab

    $o turn on the e0elo!ter tab" execute the %ollowing ste!s.

    1. +ight click anywhere on the ribbon" and then click Customi/e the +ibbon.

    Ad0ertisement

    #. 3nder Customi/e the +ibbon" on the right side o% the dialog box" select Main tabs ,i% necessary-.

    &. Check the e0elo!er check box.

  • 8/9/2019 1 Create a Macro

    3/44

    *. Click '=.

    . >ou can %ind the e0elo!er tab next to the View tab.

    Command Button

    $o !lace a command button on your worksheet" execute the %ollowing ste!s.

    1. 'n the e0elo!er tab" click nsert.

    #. n the Acti0e< Controls grou!" click Command Button.

    http://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tab
  • 8/9/2019 1 Create a Macro

    4/44

    &. rag a command button on your worksheet.

    Ad0ertisement

    Assign a Macro

    $o assign a macro ,one or more code lines- to the command button" execute the %ollowing ste!s.

    1. +ight click CommandButton1 ,make sure esign Mode is selected-.

    #. Click View Code.

    $he Visual Basic Editor a!!ears.

  • 8/9/2019 1 Create a Macro

    5/44

    &. ?lace your cursor between ?ri0ate 2ub CommandButton1@Click,- and End 2ub.

    *. Add the code line shown below.

    ote: the window on the le%t with the names 2heet1" 2heet# and 2heet& is called the ?ro(ect Ex!lorer. % the?ro(ect Ex!lorer is not 0isible" click View" ?ro(ect Ex!lorer. $o add the Code window %or the %irst sheet"click 2heet1 ,2heet1-.

    . Close the Visual Basic Editor.

    . Click the command button on the sheet ,make sure esign Mode is deselected-.

    +esult:

    Congratulations. >ou80e (ust created a macro in Excel

    Visual Basic Editor

    $o o!en the Visual Basic Editor" on the e0elo!er 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-tab
  • 8/9/2019 1 Create a Macro

    6/44

    $he Visual Basic Editor a!!ears.

    2 MsgBox: The MsgBox is a dialog box in Excel VBA

    you can use to inorm the users o your program!

    $he MsgBoxis a dialog box in Excel VBAyou can use to in%orm the users o% your !rogram. ?lace acommand buttonon your worksheet and add the %ollowing code lines:

    1. A sim!le message.

    MsgBox $his is %un

    +esult when you click the command button on the sheet:

    http://www.excel-easy.com/vba/msgbox.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/msgbox.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    7/44

    Ad0ertisement

    #. A little more ad0anced message. ;irst" enter a number into cell A1.

    MsgBox Entered 0alue is D +ange,A1-.Value

    +esult when you click the command button on the sheet:

    ote: we used the D o!erator to concatenate ,(oin- two strings. Although +ange,A1-.0alue is not a string"it works here.

    &. $o start a new line in a message" use 0bew)ine.

    MsgBox )ine 1 D 0bew)ine D )ine #

    +esult when you click the command button on the sheet:

    " #or$boo$ and #or$sheet %b&ect: 'earn more about

    the #or$boo$ and #or$sheet ob&ect in Excel VBA!%b&ect (ierarchy

    http://www.excel-easy.com/vba/workbook-worksheet-object.htmlhttp://www.excel-easy.com/vba/workbook-worksheet-object.html
  • 8/9/2019 1 Create a Macro

    8/44

    n Excel VBA" an ob(ect can contain another ob(ect" and that ob(ect can contain another ob(ect" etc. n otherwords" Excel VBA !rogramming in0ol0es working with an ob(ect hierarchy. $his !robably sounds 5uitecon%using" but we will make it clear.

    $he mother o% all ob(ects is Excel itsel%. We call it the A!!lication ob(ect. $he a!!lication ob(ect containsother ob(ects. ;or exam!le" the Workbook ob(ect ,Excel %ile-. $his can be any workbook you ha0e created.$he Workbook ob(ect contains other ob(ects" such as the Worksheet ob(ect. $he Worksheet ob(ect containsother ob(ects" such as the +ange ob(ect.

    Ad0ertisement

    $he Create a Macrocha!ter illustrates how to run code by clicking on a command button. We used the%ollowing code line:

    +ange,A1-.Value Fello

    but what we really meant was:

    A!!lication.Workbooks,createGaGmacro-.Worksheets,1-.+ange,A1-.Value Fello

    ote: the ob(ects are connected with a dot. ;ortunately" we do not ha0e to add a code line this way. $hat isbecause we !laced our command button in createGaGmacro.xls" on the %irst worksheet. Be aware that i% youwant to change di%%erent things on di%%erent worksheets to include the Worksheet ob(ect. +ead on.

    Collections

    >ou may ha0e noticed that Workbooks and Worksheets are both !lural. $hat is because they are collections.$he Workbooks collection contains all the Workbook ob(ects that are currently o!en. $he Worksheetscollection contains all the Worksheet ob(ects in a workbook.

    >ou can re%er to a member o% the collection" %or exam!le" a single Worksheet ob(ect" in three ways.

    1. 3sing the worksheet name.

    Worksheets,2ales-.+ange,A1-.Value Fello

    #. 3sing the index number ,1 is the %irst worksheet starting %rom the le%t-.

    Worksheets,1-.+ange,A1-.Value Fello

    &. 3sing the Codeame.

    2heet1.+ange,A1-.Value Fello

    $o see the Codeame o% a worksheet" o!en the Visual Basic Editor.n the ?ro(ect Ex!lorer" the %irst name is

    the Codeame. $he second name is the worksheet name ,2ales-.

    http://www.excel-easy.com/vba/create-a-macro.htmlhttp://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.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor
  • 8/9/2019 1 Create a Macro

    9/44

    ote: the Codeame remains the same i% you change the worksheet name or the order o% your worksheets sothis is the sa%est way to re%erence a worksheet. Click View" ?ro!erties Window to change the Codeame o% a

    worksheet. $here is one disad0antage" you cannot use the Codeame i% you re%erence a worksheet in adi%%erent workbook.

    )roperties and Methods

    ow let8s take a look at some !ro!erties and methods o% the Workbooks and Worksheets collection.?ro!erties are something which an collection has ,they describe the collection-" while methods do something,they !er%orm an action with an collection-.

    ?lace a command buttonon your worksheet and add the code lines:

    1. $he Add method o% the Workbooks collection creates a new workbook.

    Workbooks.Add

    ote: the Add method o% the Worksheets collection creates a new worksheet.

    #. $he Count !ro!erty o% the Worksheets collection counts the number o% worksheets in a workbook.

    MsgBox Worksheets.Count

    +esult when you click the command button on the sheet:

    ote: the Count !ro!erty o% the Workbooks collection counts the number o% acti0e workbooks.

    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-button
  • 8/9/2019 1 Create a Macro

    10/44

    * +ange %b&ect: The +ange ob&ect, -hich is the representation o a

    cell .or cells/ on your -or$sheet, is the most important ob&ect o

    Excel VBA!

    $he +ange ob&ect" which is the re!resentation o% a cell ,or cells- on your worksheet" is the most im!ortantob(ect o% Excel VBA. $his cha!ter gi0es an o0er0iew o% the !ro!erties and methods o% the +ange ob(ect.

    ?ro!erties are something which an ob(ect has ,they describe the ob(ect-" while methods do something ,they!er%orm an action with an ob(ect-.

    +ange Examples

    ?lace a command buttonon your worksheet and add the %ollowing code line:

    +ange,B&-.Value #Ad0ertisement

    +esult when you click the command button on the sheet:

    Code:

    +ange,A1:A*-.Value

    +esult:

    Code:

    +ange,A1:A#"B&:C*-.Value 19

    +esult:

    http://www.excel-easy.com/vba/range-object.htmlhttp://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/range-object.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    11/44

    Cells

    nstead o% +ange" you can also use Cells. 3sing Cells is !articularly use%ul when you want to loo!throughranges.

    Code:

    Cells,&" #-.Value #

    +esult:

    Ex!lanation: Excel VBA enters the 0alue # into the cell at the intersection o% row & and column #.

    Code:

    +ange,Cells,1" 1-" Cells,*" 1--.Value

    +esult:

    Declare a +ange %b&ect

    >ou can declare a +ange ob(ect by using the keywords im and 2et.

    Code:

    im exam!le As +ange2et exam!le +ange,A1:C*-

    exam!le.Value 6

    +esult:

    http://www.excel-easy.com/vba/loop.htmlhttp://www.excel-easy.com/vba/loop.html
  • 8/9/2019 1 Create a Macro

    12/44

    Ad0ertisement

    0elect

    An im!ortant method o% the +ange ob(ect is the 2elect method. $he 2elect method sim!ly selects a range.

    Code:

    im exam!le As +ange2et exam!le +ange,A1:C*-

    exam!le.2elect

    +esult:

    +o-s

    $he +ows !ro!erty gi0es access to a s!eci%ic row o% a range.

    Code:

    im exam!le As +ange2et exam!le +ange,A1:C*-

    exam!le.+ows,&-.2elect

    +esult:

    ote: border %or illustration only.

    Columns

    $he Columns !ro!erty gi0es access to a s!eci%ic column o% a range.

    Code:

    im exam!le As +ange2et exam!le +ange,A1:C*-

    exam!le.Columns,#-.2elect

  • 8/9/2019 1 Create a Macro

    13/44

    +esult:

    ote: border %or illustration only.

    Copy1)aste

    $he Co!y and ?aste method are used to co!y a range and to !aste it somewhere else on the worksheet.

    Code:

    +ange,A1:A#-.2elect2election.Co!y

    +ange,C&-.2electActi0e2heet.?aste

    +esult:

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

    +ange,C&:C*-.Value +ange,A1:A#-.Value

    Clear

    $o clear the content o% an Excel range" you can use the ClearContents method.

    +ange,A1-.ClearContents

    or sim!ly use:

    +ange,A1-.Value

    ote: use the Clear method to clear the content and %ormat o% a range. 3se the Clear;ormats method to clearthe %ormat only.

    Count

    With the Count !ro!erty" you can count the number o% cells" rows and columns o% a range.

  • 8/9/2019 1 Create a Macro

    14/44

    ote: border %or illustration only.

    Code:

    im exam!le As +ange2et exam!le +ange,A1:C*-

    MsgBox exam!le.Count

    +esult:

    Code:

    im exam!le As +ange2et exam!le +ange,A1:C*-

    MsgBox exam!le.+ows.Count

    +esult:

    ote: in a similar way" you can count the number o% columns o% a range.

    Variables: This chapter teaches you ho- to declare,

    initiali3e and display a variable in Excel VBA!

    http://www.excel-easy.com/vba/variables.htmlhttp://www.excel-easy.com/vba/variables.html
  • 8/9/2019 1 Create a Macro

    15/44

    $his cha!ter teaches you how to declare" initiali/e and dis!lay a variablein Excel VBA. )etting Excel VBAknow you are using a 0ariable is called declaring a 0ariable. nitiali/ing sim!ly means assigning a beginning,initial- 0alue to a 0ariable.

    ?lace a command buttonon your worksheet and add the code lines below. $o execute the code lines" clickthe command button on the sheet.

    4nteger

    nteger 0ariables are used to store whole numbers.

    im x As ntegerx +ange,A1-.Value x

    Ad0ertisement

    +esult:

    Ex!lanation: the %irst code line declares a 0ariable with name x o% ty!e nteger. ext" we initiali/e x with0alue . ;inally" we write the 0alue o% x to cell A1.

    0tring

    2tring 0ariables are used to store text.

    Code:

    im book As 2tringbook bible+ange,A1-.Value book

    +esult:

    Ex!lanation: the %irst code line declares a 0ariable with name book o% ty!e 2tring. ext" we initiali/e bookwith the text bible. Always use a!ostro!hes to initiali/e 2tring 0ariables. ;inally" we write the text o% the

    0ariable book to cell A1.

    Double

    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-button
  • 8/9/2019 1 Create a Macro

    16/44

    A 0ariable o% ty!e ouble is more accurate than a 0ariable o% ty!e nteger and can also store numbers a%terthe comma.

    Code:

    im x As ntegerx .MsgBox 0alue is D x

    +esult:

    But that is not the right 0alue We initiali/ed the 0ariable with 0alue . and we get the 0alue . What weneed is a 0ariable o% ty!e ouble.

    Code:

    im x As oublex .MsgBox 0alue is D x

    +esult:

    ote: )ong 0ariables ha0e e0en larger ca!acity. Always use 0ariables o% the right ty!e. As a result" errors areeasier to %ind and your code will run %aster.

    Boolean

    3se a Boolean 0ariable to hold the 0alue $rue or ;alse.

    Code:

    im continue As Booleancontinue $rue

    % continue $rue $hen MsgBox Boolean 0ariables are cool

  • 8/9/2019 1 Create a Macro

    17/44

    +esult:

    Ex!lanation: the %irst code line declares a 0ariable with name continue o% ty!e Boolean. ext" we initiali/econtinue with the 0alue $rue. ;inally" we use the Boolean 0ariable to only dis!lay a MsgBox i% the 0ariableholds the 0alue $rue.

    5 4 Then 0tatement: 6se the 4 Then statement in Excel

    VBA to execute code lines i a speciic condition is met!3se the 4 Then statementin Excel VBAto execute code lines i% a s!eci%ic condition is met.

    4 Then 0tatement

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im score As nteger" result As 2tringscore +ange,A1-.Value

    % score H 9 $hen result !ass

    +ange,B1-.Value resultAd0ertisement

    Ex!lanation: i% score is greater than or e5ual to 9" Excel VBA returns !ass.

    +esult when you click the command button on the sheet:

    ote: i% score is less than 9" Excel VBA !laces the 0alue o% the em!ty 0ariable result into cell B1.

    Else 0tatement

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im score As nteger" result As 2tringscore +ange,A1-.Value

    http://www.excel-easy.com/vba/if-then-statement.htmlhttp://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.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    18/44

    % score H 9 $hen result !assElse result %ailEnd %

    +ange,B1-.Value result

    Ex!lanation: i% score is greater than or e5ual to 9" Excel VBA returns !ass" else Excel VBA returns %ail.

    +esult when you click the command button on the sheet:

    ote: only i% you ha0e one code line a%ter $hen and no Else statement" it is allowed to !lace a code linedirectly a%ter $hen and to omit ,lea0e out- End % ,%irst exam!le-. 'therwise start a new line a%ter the words$hen and Else and end with End % ,second exam!le-.

    7 'oop: 'ooping is one o the most po-erul programming

    techni8ues! A loop in Excel VBA enables you to loop through a

    range o cells -ith &ust a e- codes lines!

    0ingle 'oop

    >ou can use a single loo! to loo! through a oneGdimensional range o% cells.

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im i As nteger

    ;or i 1 $o Cells,i" 1-.Value 199

    ext i Ad0ertisement

    +esult when you click the command button on the sheet:

    http://www.excel-easy.com/vba/loop.htmlhttp://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/loop.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    19/44

    Ex!lanation: $he code lines between ;or and ext will be executed six times. ;or i 1" Excel VBA entersthe 0alue 199 into the cell at the intersection o% row 1 and column 1. When Excel VBA reaches ext i" itincreases i with 1 and (um!s back to the ;or statement. ;or i #" Excel VBA enters the 0alue 199 into thecell at the intersection o% row # and column 1" etc.

    ote: it is good !ractice to always indent ,tab- the code between the words ;or and ext. $his makes yourcode easier to read.

    Double 'oop

    >ou can use a double loo! to loo! through a twoGdimensional range o% cells.

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im i As nteger" ( As nteger

    ;or i 1 $o ;or ( 1 $o #

    Cells,i" (-.Value 199 ext (

    ext i

    +esult when you click the command button on the sheet:

    Ex!lanation: ;or i 1 and ( 1" Excel VBA enters the 0alue 199 into the cell at the intersection o% row 1and column 1. When Excel VBA reaches ext (" it increases ( with 1 and (um!s back to the ;or ( statement.;or i 1 and ( #" Excel VBA enters the 0alue 199 into the cell at the intersection o% row 1 and column #.

    ext" Excel VBA ignores ext ( because ( only runs %rom 1 to #. When Excel VBA reaches ext i" itincreases i with 1 and (um!s back to the ;or i statement. ;or i # and ( 1" Excel VBA enters the 0alue 199into the cell at the intersection o% row # and column 1" etc.

    Triple 'oop

    >ou can use a tri!le loo! to loo! through twoGdimensional ranges on multi!le Excel worksheets.

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im c As nteger" i As nteger" ( As nteger

    ;or c 1 $o & ;or i 1 $o ;or ( 1 $o # Worksheets,c-.Cells,i" (-.Value 199 ext (

    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
  • 8/9/2019 1 Create a Macro

    20/44

    ext iext c

    Ex!lanation: $he only change made com!ared to the code %or the double loo! is that we ha0e added onemore loo! and added Worksheets,c-. in %ront o% Cells to get the twoGdimensional range on the %irst sheet %orc 1" the second sheet %or c # and the third sheet %or c &. ownload the Excel %ile to see this result.

    Ad0ertisement

    Do #hile 'oop

    Besides the ;or ext loo!" there are other loo!s in Excel VBA. ;or exam!le" the o While )oo!. Code!laced between o While and )oo! will be re!eated as long as the !art a%ter o While is true.

    1. ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im i As ntegeri 1

    o While i I Cells,i" 1-.Value #9 i i J 1)oo!

    +esult when you click the command button on the sheet:

    Ex!lanation: as long as i is lower than " Excel VBA enters the 0alue #9 into the cell at the intersection o%row i and column 1 and increments i by 1. n Excel VBA ,and in other !rogramming languages-" the symbol88 means becomes. t does not mean e5ual. 2o i i J 1 means i becomes i J 1. n other words: take the

    !resent 0alue o% i and add 1 to it. ;or exam!le" i% i 1" i becomes 1 J 1 #. As a result" the 0alue #9 will be!laced into column A %i0e times ,not six because Excel VBA sto!s when i e5uals -.

    #. Enter some numbers in column A.

    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-button
  • 8/9/2019 1 Create a Macro

    21/44

    &. ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im i As ntegeri 1

    o While Cells,i" 1-.Value IH Cells,i" #-.Value Cells,i" 1-.Value J 19 i i J 1)oo!

    +esult when you click the command button on the sheet:

    Ex!lanation: as long as Cells,i" 1-.Value is not em!ty ,IH means not e5ual to-" Excel VBA enters the 0alueinto the cell at the intersection o% row i and column #" that is 19 higher than the 0alue in the cell at theintersection o% row i and column 1. Excel VBA sto!s when i e5uals 4 because Cells,4" 1-.Value is em!ty.$his is a great way to loo! through any number o% rows on a worksheet.

    9 Macro Errors: This chapter teaches you ho- todeal -ith macro errors in Excel!

    $his cha!ter teaches you how to deal with macro errorsin Excel. ;irst" let8s create some errors.

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    x #+ange,A1-.Valu x

    1. Click the command button on the sheet.

    +esult:

    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/macro-errors.htmlhttp://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/macro-errors.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    22/44

    #. Click '=.

    Ad0ertisement

    $he 0ariable x is not de%ined. Because we are using the '!tion Ex!licitstatement at the start o% ourcode" we ha0e to declare all our 0ariables. Excel VBA has colored the x blue to indicate the error.

    &. n the Visual Basic Editor" click +eset to sto! the debugger.

    *. Correct the error by adding the %ollowing code line at the start o% the code.

    im x As nteger

    >ou may ha0e heard o% the techni5ue called debugging be%ore. With this techni5ue you can ste! throughyour code.

    . n the Visual Basic Editor" !lace your cursor be%ore ?ri0ate and !ress ;6.

    $he %irst 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.html
  • 8/9/2019 1 Create a Macro

    23/44

    . ?ress ;6 three more times.

    $he %ollowing error a!!ears.

    $he +ange ob(ect has a !ro!erty called Value. Value isn8t s!elled correctly here. ebugging is a great way tonot only %ind errors" but also understand code better. 'ur ebuggingexam!le !rogram shows you how tosingle ste! through your code and see the e%%ect o% each code line on your worksheet.

    0tring Manipulation: 4n this chapter, you;ll ind the

    most important unctions to manipulate strings in

    Excel VBA!

    n this cha!ter" you8ll %ind the most im!ortant %unctions to manipulate stringsin Excel VBA.

    ?lace a command buttonon your worksheet and add the code lines below. $o execute the code lines" clickthe command button on the sheet.

  • 8/9/2019 1 Create a Macro

    24/44

    im text1 As 2tring" text# As 2tringtext1 Fitext# $im

    MsgBox text1 D D text#Ad0ertisement

    +esult:

    ote: to insert a s!ace" use

    'et

    $o extract the le%tmost characters %rom a string" use )e%t.

    Code:

    im text As 2tringtext exam!le text

    MsgBox )e%t,text" *-

    +esult:

    +ight

    $o extract the rightmost characters %rom a string" use +ight. We can also directly insert text in a %unction.

    Code:

    MsgBox +ight,exam!le text" #-

    +esult:

  • 8/9/2019 1 Create a Macro

    25/44

    Mid

    $o extract a substring" starting in the middle o% a string" use Mid.

    Code:

    MsgBox Mid,exam!le text" 7" #-

    +esult:

    ote: started at !osition 7 ,t- with length #. >ou can omit the third argument i% you want to extract asubstring starting in the middle o% a string" until the end o% the string.

    'en

    $o get the length o% a string" use )en.

    Code:

    MsgBox )en,exam!le text-

    +esult:

    ote: s!ace ,!osition 6- included

    4nstr

  • 8/9/2019 1 Create a Macro

    26/44

    $o %ind the !osition o% a substring in a string" use nstr.

    Code:

    MsgBox nstr,exam!le text" am-

    +esult:

    ote: string am %ound at !osition &.

    => Date and Time: 'earn ho- to -or$ -ith dates and times

    in Excel VBA!

    ?lace a command buttonon your worksheet and add the code lines below. $o execute the code lines" clickthe command button on the sheet.

    ?ear, Month, Day o a Date

    $he %ollowing macro gets the year o% a date. $o declare a date" use the im statement. $o initiali/e a date"use the ateValue %unction.

    Code:

    im exam!leate As ate

    exam!leate ateValue,Kun 17" #919-

    MsgBox >ear,exam!leate-Ad0ertisement

    +esult:

    ote: 3se Month and ay to get the month and day o% a date.

    DateAdd

    http://www.excel-easy.com/vba/date-time.htmlhttp://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/date-time.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    27/44

    $o add a number o% days to a date" use the ateAdd %unction. $he ateAdd %unction has three arguments.;ill in d %or the %irst argument to add days. ;ill in & %or the second argument to add & days. $he thirdargument re!resents the date to which the number o% days will be added.

    Code:

    im %irstate As ate" secondate As ate

    %irstate ateValue,Kun 17" #919-secondate ateAdd,d" &" %irstate-

    MsgBox secondate

    +esult:

    ote: Change d to m to add a number o% months to a date. ?lace your cursor on ateAdd in the VisualBasic Editor and click ;1 %or hel! on the other inter0al s!eci%iers. ates are in 32 ;ormat. Months %irst"ays second. $his ty!e o% %ormat de!ends on your windows regional settings.

    Current Date and Time

    $o get the current date and time" use the ow %unction.

    Code:

    MsgBox ow

    +esult:

    (our, Minute, 0econd

    $he get the hour o% a time" use the Four %unction.

    Code:

    MsgBox Four,ow-

  • 8/9/2019 1 Create a Macro

    28/44

    +esult:

    ote: 3se Minute and 2econd to get the minute and second o% a time.

    TimeValue

    $he $imeValue %unction con0erts a string to a time serial number. $he time8s serial number is a numberbetween 9 and 1. ;or exam!le" noon ,hal%way through the day- is re!resented as 9..

    Code:

    MsgBox $imeValue,7:#9:91 am-

    +esult:

    ow" to clearly see that Excel handles times internally as numbers between 9 and 1" add the %ollowing codelines:

    im y As oubley $imeValue,97:#9:91-MsgBox y

    +esult:

  • 8/9/2019 1 Create a Macro

    29/44

    == Events: Events are actions perormed by users -hich

    trigger Excel VBA to execute code!

    Eventsare actions !er%ormed by users which trigger Excel VBAto execute code.

    #or$boo$ %pen Event

    Code added to the Workbook '!en E0ent will be executed by Excel VBA when you o!en the workbook.

    1. '!en the Visual Basic Editor.

    #. ouble click on $his Workbook in the ?ro(ect Ex!lorer.

    Ad0ertisement

    &. Choose Workbook %rom the le%t dro!Gdown list. Choose '!en %rom the right dro!Gdown list.

    *. Add the %ollowing code line to the Workbook '!en E0ent:

    MsgBox Lood Morning

    . 2a0e" close and reo!en the Excel %ile.

    +esult:

    #or$sheet Change Event

    http://www.excel-easy.com/vba/events.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/events.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor
  • 8/9/2019 1 Create a Macro

    30/44

    Code added to the Worksheet Change E0ent will be executed by Excel VBA when you change a cell on aworksheet.

    1. '!en the Visual Basic Editor.

    #. ouble click on a sheet ,%or exam!le 2heet1- in the ?ro(ect Ex!lorer.

    &. Choose Worksheet %rom the le%t dro!Gdown list. Choose Change %rom the right dro!Gdown list.

    Add the %ollowing code lines to the Worksheet Change E0ent:

    *. $he Worksheet Change E0ent listens to all changes on 2heet1. We only want Excel VBA to do somethingi% something changes in cell B#. $o achie0e this" add the %ollowing code lines:

    % $arget.Address B# $hen

    End %

    . We only want Excel VBA to show a MsgBox i% the user enters a 0alue greater than 69. $o achie0e this"add the %ollowing code line between % and End %.

    % $arget.Value H 69 $hen MsgBox Loal Com!leted

    . 'n 2heet1" enter a number greater than 69 into cell B#.

    +esult:

    http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor
  • 8/9/2019 1 Create a Macro

    31/44

    =2 Array: An array is a group o variables! 4n Excel VBA,

    you can reer to a speciic variable .element/ o an array by

    using the array name and the index number!

    An arrayis a grou! o% 0ariables. n Excel VBA" you can re%er to a s!eci%ic 0ariable ,element- o% an array byusing the array name and the index number.

    %ne@dimensional Array

    $o create a oneGdimensional array" execute the %ollowing ste!s.

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im ;ilms,1 $o - As 2tring

    ;ilms,1- )ord o% the +ings;ilms,#- 2!eed;ilms,&- 2tar Wars;ilms,*- $he Lod%ather;ilms,- ?ul! ;iction

    MsgBox ;ilms,*-Ad0ertisement

    +esult when you click the command button on the sheet:

    Ex!lanation: the %irst code line declares a 2tring array with name ;ilms. $he array consists o% %i0e elements.ext" we initiali/e each element o% the array. ;inally" we dis!lay the %ourth element using a MsgBox.

    T-o@dimensional Array

    $o create a twoGdimensional array" execute the %ollowing ste!s. $his time we are going to read the names%rom the sheet.

    http://www.excel-easy.com/vba/array.htmlhttp://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/array.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    32/44

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im ;ilms,1 $o " 1 $o #- As 2tringim i As nteger" ( As nteger

    ;or i 1 $o ;or ( 1 $o #

    ;ilms,i" (- Cells,i" (-.Value ext (

    ext i

    MsgBox ;ilms,*" #-

    +esult when you click the command button on the sheet:

    Ex!lanation: the %irst code line declares a 2tring array with name ;ilms. $he array has two dimensions. tconsists o% rows and # columns. $i!: rows go %irst" then columns. $he other two 0ariables o% ty!e ntegerare used %or the ouble )oo!to initiali/e each element o% the array. ;inally" we dis!lay the element at theintersection o% row * and column #.

    =" unction and 0ub: 4n Excel VBA, a unction can return a

    value -hile a sub cannot!

    $he di%%erence between a unctionand a subin Excel VBAis that a %unction can return a 0alue while a subcannot. ;unctions and subs become 0ery use%ul as !rogram si/e increases.

    unction

    % you want Excel VBA to !er%orm a task that returns a result" you can use a %unction. ?lace a %unction into amodule ,n the Visual Basic Editor" click nsert" Module-. ;or exam!le" the %unction with name Area.

    ;unction Area,x As ouble" y As ouble- As ouble

    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/loop.html#double-loophttp://www.excel-easy.com/vba/function-sub.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/loop.html#double-loophttp://www.excel-easy.com/vba/function-sub.html
  • 8/9/2019 1 Create a Macro

    33/44

    Area x N y

    End ;unctionAd0ertisement

    Ex!lanation: $his %unction has two arguments ,o% ty!e ouble- and a return ty!e ,the !art a%ter Asalso o% ty!e ouble-. >ou can use the name o% the %unction ,Area- in your code to indicate which result youwant to return ,here x N y-.

    >ou can now re%er to this %unction ,in other words call the %unction- %rom somewhere else in your code bysim!ly using the name o% the %unction and gi0ing a 0alue %or each argument.

    ?lace a command buttonon your worksheet and add the %ollowing code lines:

    im / As ouble

    / Area,&" - J #

    MsgBox /

    Ex!lanation: $he %unction returns a 0alue so you ha0e to 8catch8 this 0alue in your code. >ou can use another0ariable ,/- %or this. ext" you can add another 0alue to this 0ariable ,i% you want-. ;inally" dis!lay the 0alueusing a MsgBox.

    +esult when you click the command button on the sheet:

    0ub

    % you want Excel VBA to !er%orm some actions" you can use a sub. ?lace a sub into a module ,n the VisualBasic Editor" click nsert" Module-. ;or exam!le" the sub with name Area.

    2ub Area,x As ouble" y As ouble-

    MsgBox x N y

    End 2ub

    Ex!lanation: $his sub has two arguments ,o% ty!e ouble-. t does not ha0e a return ty!e >ou can re%er tothis sub ,call the sub- %rom somewhere else in your code by sim!ly using the name o% the sub and gi0ing a0alue %or each argument.

    ?lace a command buttonon your worksheet and add the %ollowing code line:

    Area &"

    +esult 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-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    34/44

    Can you see the di%%erence between the %unction and the subO $he %unction returned the 0alue 1. We addedthe 0alue # to this result and dis!layed the %inal result. When we called the sub we had no more control o0erthe result ,1- because a sub cannot return a 0alue

    =* Application %b&ect: The mother o all ob&ects is Excel itsel! #e

    call it the Application ob&ect! The application ob&ect gives access to

    a lot o Excel related options!

    $he mother o% all ob(ects is Excel itsel%. We call it the Application ob&ect. $he a!!lication ob(ect gi0esaccess to a lot o% Excel related o!tions.

    #or$sheetunction

    >ou can use the Worksheet;unction !ro!erty in Excel VBAto access Excel %unctions.

    1. ;or exam!le" !lace a command buttonon your worksheet and add the %ollowing code line:

    +ange,A&-.Value A!!lication.Worksheet;unction.A0erage,+ange,A1:A#--Ad0ertisement

    When you click the command button on the worksheet" Excel VBA calculates the a0erage o% the0alues in cell A1 and cell A# and !laces the result into cell A&.

    ote: instead o% A!!lication.Worksheet;unction.A0erage" sim!ly use Worksheet;unction.A0erage. % youlook at the %ormula bar" you can see that the %ormula itsel% is not inserted into cell A&. $o insert the %ormulaitsel% into cell A&" use the %ollowing code line:

    +ange,A&-.Value AVE+ALE,A1:A#-

    0creen6pdating

    2ometimes you may %ind it use%ul to disable screen u!dating ,to a0oid %lickering- while executing code. As aresult" your code will run %aster.

    1. ;or exam!le" !lace a command buttonon your worksheet and add the %ollowing code lines:

    http://www.excel-easy.com/vba/application-object.htmlhttp://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/application-object.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    35/44

    im i As nteger

    ;or i 1 $o 19999 +ange,A1-.Value i

    ext i

    When you click the command button on the worksheet" Excel VBA dis!lays each 0alue a tiny %raction o% asecond and this can take some time.

    #. $o s!eed u! the !rocess" u!date the code as %ollows.

    im i As nteger

    A!!lication.2creen3!dating ;alse

    ;or i 1 $o 19999 +ange,A1-.Value i

    ext i

    A!!lication.2creen3!dating $rue

    As a result" your code will run much %aster and you will only see the end result ,19999-.

    DisplayAlerts

    >ou can instruct Excel VBA not to dis!lay alerts while executing code.

    1. ;or exam!le" !lace a command buttonon your worksheet and add the %ollowing code line:

    Acti0eWorkbook.Close

    When you click the command button on the worksheet" Excel VBA closes your Excel %ile and asks you tosa0e the changes you made.

    #. $o instruct Excel VBA not to dis!lay this alert while executing code" u!date the code as %ollows.

    A!!lication.is!layAlerts ;alse

    Acti0eWorkbook.Close

    A!!lication.is!layAlerts $rue

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    36/44

    As a result" Excel VBA closes your Excel %ile" without asking you to sa0e the changes you made. Anychanges are lost.

    Calculation

    By de%ault" calculation is set to automatic. As a result" Excel recalculates the workbook automatically eachtime a 0alue a%%ecting a %ormula changes. % your workbook contains many com!lex %ormulas" you can s!eedu! your macro by setting calculation to manual.

    1. ;or exam!le" !lace a command buttonon your worksheet and add the %ollowing code line:

    A!!lication.Calculation xlCalculationManual

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

    #. >ou can 0eri%y this by clicking on ;ile" '!tions" ;ormulas.

    &. ow when you change the 0alue o% cell A1" the 0alue o% cell B1 is not recalculated.

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://www.excel-easy.com/vba/create-a-macro.html#command-button
  • 8/9/2019 1 Create a Macro

    37/44

    >ou can manually recalculate the workbook by !ressing ;7.

    *. n most situations" you will set calculation to automatic again at the end o% your code. 2im!ly add the%ollowing code line to achie0e this.

    A!!lication.Calculation xlCalculationAutomatic

    = Active Controls: 'earn ho- to create Active controls

    such as command buttons, text boxes, list boxes etc!

    )earn how to create Active controlssuch as command buttons" text boxes" list boxes etc. $o create anActi0e< control in Excel VBA" execute the %ollowing ste!s.

    1. 'n the e0elo!er tab" click nsert.

    #. ;or exam!le" in the Acti0e< Controls grou!" click Command Button to insert a command button control.

    Ad0ertisement

    &. rag a command button on your worksheet.

    *. +ight click the command button ,make sure esign Mode is selected-.

    . Click View Code.

    http://www.excel-easy.com/vba/activex-controls.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tabhttp://www.excel-easy.com/vba/activex-controls.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#developer-tab
  • 8/9/2019 1 Create a Macro

    38/44

    ote: you can change the ca!tion and name o% a control by right clicking on the control ,make sure esignMode is selected- and then clicking on ?ro!erties. Change the ca!tion o% the command button to 8A!!lyBlue $ext Color8. ;or now" we will lea0e CommandButton1 as the name o% the command button.

    $he Visual Basic Editor a!!ears.

    . Add the code line shown below between ?ri0ate 2ub CommandButton1@Click,- and End 2ub.

    4. 2elect the range B#:B* and click the command button ,make sure esign Mode is deselected-.

    +esult:

  • 8/9/2019 1 Create a Macro

    39/44

    =5 6serorm: This chapter teaches you ho- to create an

    Excel VBA 6serorm!

    $his cha!ter teaches you how to create an Excel VBA 6serorm. $he 3ser%orm we are going to create looksas %ollows:

    Ad0ertisement

    Add the Controls

    $o add the controls to the 3ser%orm" execute the %ollowing ste!s.

    1. '!en the Visual Basic Editor. % the ?ro(ect Ex!lorer is not 0isible" click View" ?ro(ect Ex!lorer.

    #. Click nsert" 3ser%orm. % the $oolbox does not a!!ear automatically" click View" $oolbox. >our screenshould be set u! as below.

    http://www.excel-easy.com/vba/userform.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/userform.htmlhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor
  • 8/9/2019 1 Create a Macro

    40/44

    &. Add the controls listed in the table below. 'nce this has been com!leted" the result should be consistentwith the !icture o% the 3ser%orm shown earlier. ;or exam!le" create a text box control by clicking on$extBox %rom the $oolbox. ext" you can drag a text box on the 3ser%orm. When you arri0e at the Car%rame" remember to draw this %rame %irst be%ore you !lace the two o!tion buttons in it.

    *. Change the names and ca!tions o% the controls according to the table below. ames are used in the ExcelVBA code. Ca!tions are those that a!!ear on your screen. t is good !ractice to change the names o%controls. $his will make your code easier to read. $o change the names and ca!tions o% the controls" clickView" ?ro!erties Window and click on each control.

    Control ame Caption

    3ser%orm inner?lanner3ser;orm inner ?lanner

    $ext Box ame$extBox

    $ext Box ?hone$extBox

    )ist Box City)istBox

    Combo Box innerComboBox

    Check Box ateCheckBox1 Kune 1&th

    Check Box ateCheckBox# Kune #9th

    Check Box ateCheckBox& Kune #4th

    ;rame Car;rame Car

    '!tion Button Car'!tionButton1 >es

    '!tion Button Car'!tionButton# o$ext Box Money$extBox

    2!in Button Money2!inButton

  • 8/9/2019 1 Create a Macro

    41/44

    Command Button '=Button '=

    Command Button ClearButton Clear

    Command Button CancelButton Cancel

    4 )abels o need to change ame:" ?hone umber:" etc.

    ote: a combo box is a dro!Gdown list %rom where a user can select an item or %ill in hisPher own choice.'nly one o% the o!tion buttons can be selected.

    0ho- the 6serorm

    $o show the 3ser%orm" !lace a command buttonon your worksheet and add the %ollowing code line:

    ?ri0ate 2ub CommandButton1@Click,-

    inner?lanner3ser;orm.2how

    End 2ub

    We are now going to create the 2ub 3ser;orm@nitiali/e. When you use the 2how method %or the 3ser%orm"this sub will automatically be executed.

    1. '!en the Visual Basic Editor.

    #. n the ?ro(ect Ex!lorer" right click on inner?lanner3ser;orm and then click View Code.

    &. Choose 3ser%orm %rom the le%t dro!Gdown list. Choose nitiali/e %rom the right dro!Gdown list.

    *. Add the %ollowing code lines:

    ?ri0ate 2ub 3ser;orm@nitiali/e,-

    8Em!ty ame$extBoxame$extBox.Value

    8Em!ty ?hone$extBox?hone$extBox.Value

    8Em!ty City)istBoxCity)istBox.Clear

    8;ill City)istBoxWith City)istBox .Addtem 2an ;rancisco .Addtem 'akland .Addtem +ichmondEnd With

    8Em!ty innerComboBox

    innerComboBox.Clear

    8;ill innerComboBoxWith innerComboBox .Addtem talian

    http://www.excel-easy.com/vba/create-a-macro.html#command-buttonhttp://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#visual-basic-editor
  • 8/9/2019 1 Create a Macro

    42/44

    .Addtem Chinese .Addtem ;rites and MeatEnd With

    83ncheck ataCheckBoxesateCheckBox1.Value ;alseateCheckBox#.Value ;alseateCheckBox&.Value ;alse

    82et no car as de%aultCar'!tionButton#.Value $rue

    8Em!ty Money$extBoxMoney$extBox.Value

    82et ;ocus on ame$extBoxame$extBox.2et;ocus

    End 2ub

    Ex!lanation: text boxes are em!tied" list boxes and combo boxes are %illed" check boxes are unchecked" etc.

    Ad0ertisement

    Assign the Macros

    We ha0e now created the %irst !art o% the 3ser%orm. Although it looks neat already" nothing will ha!!en yetwhen we click the command buttons on the 3ser%orm.

    1. '!en the Visual Basic Editor.

    #. n the ?ro(ect Ex!lorer" double click on inner?lanner3ser;orm.

    &. ouble click on the Money s!in button.

    *. Add the %ollowing code line:

    ?ri0ate 2ub Money2!inButton@Change,-

    Money$extBox.$ext Money2!inButton.Value

    End 2ub

    Ex!lanation: this code line u!dates the text box when you use the s!in button.

    . ouble click on the '= button.

    . Add the %ollowing code lines:

    ?ri0ate 2ub '=Button@Click,-

    im em!ty+ow As )ong

    8Make 2heet1 acti0e2heet1.Acti0ate

    http://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editorhttp://www.excel-easy.com/vba/create-a-macro.html#visual-basic-editor
  • 8/9/2019 1 Create a Macro

    43/44

    8etermine em!ty+owem!ty+ow Worksheet;unction.CountA,+ange,A:A-- J 1

    8$rans%er in%ormationCells,em!ty+ow" 1-.Value ame$extBox.ValueCells,em!ty+ow" #-.Value ?hone$extBox.ValueCells,em!ty+ow" &-.Value City)istBox.ValueCells,em!ty+ow" *-.Value innerComboBox.Value

    % ateCheckBox1.Value $rue $hen Cells,em!ty+ow" -.Value ateCheckBox1.Ca!tion

    % ateCheckBox#.Value $rue $hen Cells,em!ty+ow" -.Value Cells,em!ty+ow" -.Value D DateCheckBox#.Ca!tion

    % ateCheckBox&.Value $rue $hen Cells,em!ty+ow" -.Value Cells,em!ty+ow" -.Value D DateCheckBox&.Ca!tion

    % Car'!tionButton1.Value $rue $hen Cells,em!ty+ow" -.Value >esElse Cells,em!ty+ow" -.Value oEnd %

    Cells,em!ty+ow" 4-.Value Money$extBox.Value

    End 2ub

    Ex!lanation: %irst" we acti0ate 2heet1. ext" we determine em!ty+ow. $he 0ariable em!ty+ow is the %irst

    em!ty row and increases e0ery time a record is added. ;inally" we trans%er the in%ormation %rom the3ser%orm to the s!eci%ic columns o% em!ty+ow.

    4. ouble click on the Clear button.

    6. Add the %ollowing code line:

    ?ri0ate 2ub ClearButton@Click,-

    Call 3ser;orm@nitiali/e

    End 2ub

    Ex!lanation: this code line calls the 2ub 3ser;orm@nitiali/e when you click on the Clear button.

    7. ouble click on the Cancel Button.

    19. Add the %ollowing code line:

    ?ri0ate 2ub CancelButton@Click,-

    3nload Me

    End 2ub

    Ex!lanation: this code line closes the 3ser%orm when you click on the Cancel button.

  • 8/9/2019 1 Create a Macro

    44/44