MS. Excell VBA-#3, July 24, 2013

download MS. Excell VBA-#3, July 24, 2013

of 10

Transcript of MS. Excell VBA-#3, July 24, 2013

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    1/10

    VBA Excel 2007

    MS Access 2007

    Excel Microsoft

    http://www.googleadservices.com/pagead/aclk?sa=L&ai=C9Wle5E_vUeTEO6HNige0hoGYA_uD29oDg9y18Fna2R4QASDcj4ECUPKol6P4_____wFg6QKgAa_PxP4DyAECqAMByAPRBKoEkQFP0DWq_ZitgYvlLt797B4rLls3SAONhTIrANmmsDoIN-OFzN4Bq6ImPb6-KUoxkYUwuFucZqZuUJNXccbT9-OhK0uupyFcw4ZGtZ-0YHuSBSMzsavlacVDJ5Wu7N5ZM3dhl20DoxWmHEU_eHSVTszunQxcwCAsZhnMXEQ3Y4THXn08eVV-Fz-uheNyD_ljo3CqiAYBoAYCgAe5sLsB&num=1&cid=5Ghy3vBjqWWfWLPJlVlGZMKy&sig=AOD64_2jWZJ1i3cEfuyb8hgZtbsXA9qFuA&client=ca-pub-3968514660870014&adurl=http://www.tekscan.com/interface-load-gauge%3Futm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_term%3Dload%2Bgage%26utm_content%3Dad5%26utm_campaign%3Dpressure%2Bdisplay&nm=1http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3968514660870014&format=fp_al_lp&output=html&h=90&w=160&lmt=1291793212&ad_type=text_image&flash=11.8.800&url=http%3A%2F%2Fwww.functionx.com%2Fvbaexcel%2Ffundamentals%2FLesson3.htm&dt=1374638051254&bpp=49&bdt=806&shv=r20130718&cbv=r20130206&saldr=sa&correlator=1374638051528&frm=20&adk=1599413332&ga_vid=1874035717.1374638052&ga_sid=1374638052&ga_hid=1604922000&ga_fc=0&u_tz=420&u_his=1&u_java=1&u_h=768&u_w=1366&u_ah=728&u_aw=1366&u_cd=32&u_nplug=14&u_nmime=56&dff=verdana&dfs=13&adx=229&ady=268&biw=1349&bih=624&oid=3&ref=http%3A%2F%2Fwww.functionx.com%2Fvbaexcel%2F&fu=0&ifi=1&pfi=16&dtd=583&xpc=q6q3qZu0pp&p=http%3A//www.functionx.com&kw_type=radlink&prev_fmts=160x90_0ads_al&rt=ChBR70_iAArt-grio8j0ABObEg9FeGNlbCBNaWNyb3NvZnQaCGQJgFZ3QEJIIPSkmsYCKAFI9KSaxgJSEwjoo8rlnce4AhUMnOIKHXYQAEM&hl=en&kw0=VBA+Excel+2007&kw1=MS+Access+2007&kw2=Excel+Microsoft&okw=Excel+Microsofthttp://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3968514660870014&format=fp_al_lp&output=html&h=90&w=160&lmt=1291793212&ad_type=text_image&flash=11.8.800&url=http%3A%2F%2Fwww.functionx.com%2Fvbaexcel%2Ffundamentals%2FLesson3.htm&dt=1374638051254&bpp=49&bdt=806&shv=r20130718&cbv=r20130206&saldr=sa&correlator=1374638051528&frm=20&adk=1599413332&ga_vid=1874035717.1374638052&ga_sid=1374638052&ga_hid=1604922000&ga_fc=0&u_tz=420&u_his=1&u_java=1&u_h=768&u_w=1366&u_ah=728&u_aw=1366&u_cd=32&u_nplug=14&u_nmime=56&dff=verdana&dfs=13&adx=229&ady=268&biw=1349&bih=624&oid=3&ref=http%3A%2F%2Fwww.functionx.com%2Fvbaexcel%2F&fu=0&ifi=1&pfi=16&dtd=583&xpc=q6q3qZu0pp&p=http%3A//www.functionx.com&kw_type=radlink&prev_fmts=160x90_0ads_al&rt=ChBR70_iAArt9grio8j0ABObEg5NUyBBY2Nlc3MgMjAwNxoIrETwnu9wLjcg9KSaxgIoAUj0pJrGAlITCOijyuWdx7gCFQyc4goddhAAQw&hl=en&kw0=VBA+Excel+2007&kw1=MS+Access+2007&kw2=Excel+Microsoft&okw=MS+Access+2007http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3968514660870014&format=fp_al_lp&output=html&h=90&w=160&lmt=1291793212&ad_type=text_image&flash=11.8.800&url=http%3A%2F%2Fwww.functionx.com%2Fvbaexcel%2Ffundamentals%2FLesson3.htm&dt=1374638051254&bpp=49&bdt=806&shv=r20130718&cbv=r20130206&saldr=sa&correlator=1374638051528&frm=20&adk=1599413332&ga_vid=1874035717.1374638052&ga_sid=1374638052&ga_hid=1604922000&ga_fc=0&u_tz=420&u_his=1&u_java=1&u_h=768&u_w=1366&u_ah=728&u_aw=1366&u_cd=32&u_nplug=14&u_nmime=56&dff=verdana&dfs=13&adx=229&ady=268&biw=1349&bih=624&oid=3&ref=http%3A%2F%2Fwww.functionx.com%2Fvbaexcel%2F&fu=0&ifi=1&pfi=16&dtd=583&xpc=q6q3qZu0pp&p=http%3A//www.functionx.com&kw_type=radlink&prev_fmts=160x90_0ads_al&rt=ChBR70_iAArt7Ario8j0ABObEg5WQkEgRXhjZWwgMjAwNxoIWrzOSAWDUyMg9KSaxgIoAUj0pJrGAlITCOijyuWdx7gCFQyc4goddhAAQw&hl=en&kw0=VBA+Excel+2007&kw1=MS+Access+2007&kw2=Excel+Microsoft&okw=VBA+Excel+2007http://www.google.com/url?ct=abg&q=https://www.google.com/adsense/support/bin/request.py%3Fcontact%3Dabg_afc%26url%3Dhttp://www.functionx.com/vbaexcel/fundamentals/Lesson3.htm%26gl%3DID%26hl%3Den%26client%3Dca-pub-3968514660870014&usg=AFQjCNEjalYfCPZwx_Fv-waDf8bsswh4hw
  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    2/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 2/10

    equ re ar a e ec ara on c ec ox

    3. Click OK and return to Microsoft Excel

    4. To close Microsoft Exce l, click the Office butt on and click Exit Excel

    5. When asked whether you want to save, click No

    Declaring Many Variables

    In a regular applicat ion, it is not unusual to want t o use many variables. Once again, you should make

    it a habit to always declare a variable before using it. To declare a new variable after declaring a firstone, you can simply go to the next line and use the Dim keyword to declare the new variable. Here is

    an example:

    Sub Exercise()

    Dim Something

    Dim Whatever

    End Sub

    In the same way, you can declare as many variables as you want. Instead of declaring each variableon its own line, you can declare more than one variable on the same line. To do this, use one Dim

    keyword and separate the names of variables with commas. Here are examples:

    Sub Exercise()

    Dim Father, Mother

    Dim Son, Daughter, Nephew, Niece

    Dim GrandMa

    End Sub

    Notice that each line uses its own Dimkeyword and every new line of declaration(s) must have a

    Dimkeyword.

    Practical Learning: Creating a Macro

    1. Start Microsoft Excel

    2. On the Ribbon, click View

    3. In the Macros sect ion, click the arrow under the Macros button and click Record Macro...

    4. Set the Name of the macro as Variablesand click OK

    5. While in the document, type =0

    6. On the Formula Bar, click the Enter button

    7. In the Macros sect ion of the Ribbon, click the arrow under the Macros button and click Stop

    Recording

    8. To save the document, in the Quick Access Toolbar, click the Save button

    9. Type the name of the file as Exercise1and click Save.If a message box comes up, read it and click Yes

    10. To open Microsoft Visual Basic, in the Macros sect ion of the Ribbon, click the Macros button(click the button itself)

    11. In the Macros dialog box, make sure Exercise1 is selected and click Edit.Notice the Option Explicit line

    Value Assignment

    We saw that when you declare a variable, the computer reserves a memory space for it but the

    space is kept empty. After declaring the value, you can store a value you want in the memory thatwas reserved for it.

    To store a value in the memory reserved for a variable, you can assign a value to the variable. To do

    this, type the name of the variable, followed by the assignment operator which is =, followed by thevalue you want to store. Here is an example:

    Sub Exercise()

    Dim Value

    Value = 9374

    End Sub

    As we will learn in the next few lessons, there are different t es of values ou will use in our

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    3/10

    http://ad-apac.doubleclick.net/6k;h=v8/3e29/c/1c1/%2a/n;272861365;0-0;0;98807945;2321-160/600;54547528/54433033/1;u=xbAAXbk6qaFl--P_aIsQEU10hM_YWf5gTxzscuF1W8zUw9qX52ZG3RcBGw95IlyyHJkJkGeFln-DkLcztENsTvbiK4jOuYu04M8A;~sscs=%3fhttp://adclick.g.doubleclick.net/aclk?sa=L&ai=CTxua5U_vUbukAqSNiAfoqoDYBLbZjOQCxv-S0zS25eeyXBABIABQgMfhxARg6QKCARdjYS1wdWItMzk2ODUxNDY2MDg3MDAxNMgBCagDAaoEkAFP0F069z3pQCRxfDMk9sDCCSOcYuGQPzRs823ZLVxqlsQCbIXSv769RF9ZIs4iHFL1pyQ6tpi_hg08Cf94yfHb2BrdjOh15UnaUp2PgSoS6m3UV2liIfHJkQRUgrZNl8VSqQwSMFxiUpvV6asLdOOzSI2I1I6cxkAvHBCdn28BE8WqvTaaPoOVNl0oYcc23paABvG09rTG5ZGvzQE&num=1&sig=AOD64_1ZHjD05mjghcuFEa9En2fGC1vPbg&client=ca-pub-3968514660870014&adurl=http%3a%2f%2fwww.santika.com
  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    4/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 4/10

    Byte

    To declare a variable that would hold natural numbers that range from 0 to 255, use the Bytedatatype. Here is an example:

    Sub Exercise()

    Dim StudentAge As Byte

    End Sub

    There is no type character for the Bytedata type.

    After declaring the variable, you can assign it a small positive number. Here is an example:

    Sub Exercise()

    Dim Value As Byte

    Value = 246

    End Sub

    You can also use the number in hexadecimal format as long as the number is less than 255.

    If you give either a negative value or a value higher to 255, when you attempt to access it, you

    would receive an error:

    To convert a value to a small number, you can use CByte(). The formula to use would be:

    Number= CByte(Value to Convert to Byte)

    When using CByte(), enter the value to convert in the parentheses.

    Practical Learning: Using Byte Variables

    1. In the code, c lick ActiveCell, press Home, press Enter, and press the up arrow key

    2. To use byte variables, change the code as follows:

    Sub Variables()

    Dim Shirts As Byte

    Dim Pants As Byte

    Dim OtherItems As Byte

    Dim TotalItems As Byte

    Shirts = 6

    Pants = 4

    OtherItems = 2

    TotalItems = Shirts + Pants + OtherItems

    ActiveCell.FormulaR1C1 = TotalItems

    End Sub

    3. To return to Microsoft Excel, on the Standard toolbar, click the View Microsoft Excel button

    4. In Microsoft Excel, click any box

    5. In the Code sect ion of the Ribbon, click the Macros button

    6. In the Macros dialog box, make sure Exercise1 is selected and click Run

    7. To return to Microsoft Visual Basic, in the Code sec tion of the Ribbon, click Visual Basic

    Integer

    To declare a variable that would hold a number that ranges from -32768 to 32767, use the Integerdata type. Here is an example of dec laring an integer variable:

    Sub Exercise()

    Dim Tracks As Integer

    End Sub

    Instead of using As Integer, you can use the % type character. Therefore, the above declarationcould be done as follows:

    Sub Exercise()

    Dim Tracks%

    End Sub

    After declaring the variable, you can assign the desired value to it. If you assign a value lower than-32768 or higher than 32767, when you decide to use it, you would receive an error.

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    5/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 5/10

    If you have a value that needs to be converted into a natural number, you can use CInt()using thefollowing formula:

    Number= CInt(Value to Convert)

    Between the parentheses of CInt(), enter the value, text, or expression that needs to be converted.

    Long

    A long integer is a number that can be used for a variable involving greater numbers than integers. To

    declare a variable that would hold such a large number, use the Longdata type. Here is an example:

    Sub Exercise()

    Dim Population As Long

    End Sub

    The type character for the Long data type is @. The above variable could be declared as:

    Sub Exercise()

    Dim Population@

    End Sub

    A Longvariable can store a value between 2,147,483,648 and 2,147,483,647 (remember that the

    commas are used to make the numbers easy to read; do not be used them in your code). Therefore,after declaring a Longvariable, you can assign it a number in that range.

    To convert a value to a long integer, call CLng()using the following formula:

    Number= CLng(Value to Convert)

    To convert a value to long, enter it in the parentheses of CLng().

    Decimal Variables

    Single Precision

    In computer programming, a decimal number is one that represents a fraction. Examples are 1.85 or

    426.88. If you plan to use a variable that would that type of number but precision is not your mainconcern, declare it using the Singledata type. Here is an example:

    Sub Exercise()

    Dim Distance As Single

    End Sub

    The type character for the Single data type is !. Based on this, the above declaration could be doneas:

    Sub Exercise()

    Dim Distance!

    End Sub

    A Singlevariable can hold a number between 1.401298e45and 3.402823e38. for negative values or

    between 1.401298e45and 3.402823e38for positive values.

    If you have a value that needs to be converted, use CSng()with the following formula:

    Number= CSng(Value to Convert)

    In the parentheses of CSng(), enter the value to be converted.

    Double Precision

    If you want to use a decimal number that requires a good deal of precision, declare a variable using

    the Doubledata type. Here is an example of declaring a Doublevariable:

    Sub Exercise()

    Dim Distance As Double

    End Sub

    Instead of As Double, the t ype character you can use is #:

    Sub Exercise()

    Dim Distance#

    End Sub

    A Doublevariable can hold a number between 1.79769313486231e308and

    4.94065645841247e324 for negative values or between 4.94065645841247e324 and

    1.79769313486231e308for positive values.

    To convert a value to double-precision, use CDbl()with the following formula:

    Number = CDbl(Value to Convert)

    In the parentheses of CDbl(), enter the value that needs to be converted.

    Practical Learning: Using Decimal Variables

    1. Change the code as follows:

    Sub Variables()

    Dim Side As Double

    Dim Perimeter As Double

    Side = 32.75

    Perimeter = Side * 4

    http://solvehunger.feedingamerica.org/?s_src=Y13YAPSGB
  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    6/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 6/10

    ActiveCell.FormulaR1C1 = Perimeter

    End Sub

    2. To return to Microsoft Excel, on the Standard toolbar, click the View Microsoft Excel button

    3. In Microsoft Excel, click any box

    4. In the Code sect ion of the Ribbon, click the Macros button

    5. In the Macros dialog box, make sure Exercise1 is selected and click Run

    6. To return to Microsoft Visual Basic, in the Code sec tion of the Ribbon, click Visual Basic

    A String

    A string is a character or a combination of characters that constitute text of any kind and almost anylength. To declare a string variable, use the Stringdata type. Here is an example:

    Sub Exercise()

    Dim CountryName As String

    End Sub

    The type character for the String data type is $. Therefore, the above declaration could be writtenas:

    Sub Exercise()

    Dim CountryName$End Sub

    As mentioned already, after declaring a variable, you can assign a value to it. The value of a string

    variable must be inc luded inside of double-quotes. Here is an example:

    Sub Exercise()

    Dim CountryName As String

    CountryName = "Brsil"

    End Sub

    If you have a value that is not primarily text and you want to convert it to a string, use CStr()with

    the following formula:

    CStr(Value To Convert to String)

    In the parentheses of the CStr(), enter the value that you want to c onvert to string.

    Practical Learning: Using a String

    1. Change the code as follows:

    Sub Variables()

    Dim CustomerName As String

    CustomerName = "Paul Bertrand Yamaguchi"

    ActiveCell.FormulaR1C1 = CustomerName

    End Sub

    2. To return to Microsoft Excel, on the Standard toolbar, click the View Microsoft Excel button

    3. In Microsoft Excel, click any box

    4. In the Code sect ion of the Ribbon, click the Macros button

    5. In the Macros dialog box, make sure Exercise1 is selected and click Run

    6. To return to Microsoft Visual Basic, in the Code sec tion of the Ribbon, click Visual Basic

    Currency Values

    The Currencydata type is used to deal with monetary values. Here is an example of declaring it:

    Sub Exercise()

    Dim StartingSalary As Currency

    End Sub

    Instead of using the As Currency expression, you can use @ as the type character to declare acurrency variable. Here is an example of dec laring it:

    Sub Exercise()

    Dim StartingSalary@

    End Sub

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    7/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 7/10

    A variable declared with the Currency keyword can store a value between 922,337,203,685,477.5808 and 922,337,203,685,477.5807. Once again, keep in mind that thecommas here are used only to make the number easy to read. Don't use the commas in a number in

    your code. Also, when assigning a value to a currency-based variable, do not use the currencysymbol.

    Here is an example of assigning a currency number to a variable:

    Sub Exercise()

    Dim StartingSalary As Currency

    StartingSalary = 66500

    End Sub

    If you want to convert a value to c urrency, use CCur() with the following formula:

    Number = CCur(Value to Convert)

    To perform this conversion, enter the value in the parentheses of CCur().

    Practical Learning: Using Currency Values

    1. Change the code as follows:

    Sub Variables()

    Dim NumberOfShirts As Byte

    Dim PriceOneShirt As Currency

    Dim TotalPriceShirts As Currency

    NumberOfShirts = 5

    PriceOneShirt = 1.25

    TotalPriceShirts = NumberOfShirts * PriceOneShirt

    ActiveCell.FormulaR1C1 = TotalPriceShirtsEnd Sub

    2. To return to Microsoft Excel, on the Standard toolbar, click the View Microsoft Excel button

    3. In Microsoft Excel, click any box

    4. In the Code sect ion of the Ribbon, click the Macros button

    5. In the Macros dialog box, make sure Exercise1 is selected and click Run

    6. To return to Microsoft Visual Basic, in the Code sec tion of the Ribbon, click Visual Basic

    A Date

    In Visual Basic, a Datedata type can be used to store a date value. Therefore, to declare either adate or a time variables, use the Datedata type. Here is an example:

    Sub Exercise()

    Dim DateOfBirth As Date

    End Sub

    After declaring the variable, you can assign it a value. A date value must be included between two #signs. Here is an example:

    Sub Exercise()

    Dim DateOfBirth As Date

    DateOfBirth = #10/8/1988#

    End Sub

    There are various formats you can use for a date. We will deal with them in another lesson.

    If you have a string or an expression that you want to convert to a date value, use CDate()basedon the following formula:

    Result= CDate(Value to Convert)

    In the parentheses of CDate(), enter the value that needs to be converted.

    Practical Learning: Using a Date

    1. Change the code as follows:

    Sub Variables()

    Dim DepositDate As Date

    DepositDate = #2/5/2008#

    ActiveCell.FormulaR1C1 = DepositDate

    End Sub

    2. To return to Microsoft Excel, on the Standard toolbar, click the View Microsoft Excel button

    3. In Microsoft Excel, click any box

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    8/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 8/10

    4. In the Code sect ion of the Ribbon, click the Macros button

    5. In the Macros dialog box, make sure Exercise1 is selected and click Run

    6. To return to Microsoft Visual Basic, in the Code sec tion of the Ribbon, click Visual Basic

    A Time

    In Visual Basic, the Datedata type can also be used to store a time value. Here is an example of

    declaring a variable that can hold a time value:

    Sub Exercise()

    Dim ShiftTimeIn As Date

    End Sub

    After declaring the variable, to assign a value to it, include the value between two # signs. The valuefollows different rules from a date.

    To convert a value or an expression to time, use CDate().

    Any-Type Variables

    A Variant

    So far, we declared variables knowing the types of values we wanted them to hold. VBA provides auniversal (or vague) data type you can use for any type of value. The Variant data type is used todeclare a variable whose type is not explicitly specified. This means that a Variant data type can hold

    any type of value you want.

    Here are examples of Variant-declared variables that hold different types of values:

    Sub Exercise()

    Dim FullName As Variant

    Dim EmploymentStatus As Variant

    Dim HourlySalary As Variant

    Dim DateHired As Variant

    FullName = "Patricia Katts"

    EmploymentStatus = 2

    HourlySalary = 35.65

    DateHired = #6/22/2004#

    End Sub

    A Variable Without a Data Type

    In the variables we declared in the last few sections, we specified a data type for each. You candeclare a variable without giving its data type. Here are examples:

    Sub Exercise()

    Dim FullName

    Dim EmploymentStatus

    Dim HourlySalary

    Dim DateHired

    End Sub

    Of course, you can declare more than one variable on the same line.

    To indicate how much space is needed for the variable, you must assign it a value. Here are

    examples:

    Sub Exercise()

    Dim FullName

    Dim EmploymentStatus

    Dim HourlySalary

    Dim DateHired

    FullName = "Patricia Katts"

    EmploymentStatus = 2

    HourlySalary = 35.65

    DateHired = #6/22/2004#

    End Sub

    Once the variable holds a value, you can use it as you see fit.

    The Scope or Lifetime of a Variable

    Introduction

    So far, we were declaring our variables between the SubName and the End Sub lines. Such avariable is referred to as a local variable. A local variable is confined to the area where it is declared.

    Here is an example:

    Option Explicit

    Sub Exercise()

    Dim FirstName As String

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    9/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    www.functionx.com/vbaexcel/fundamentals/Lesson3.htm 9/10

    FirstName = "Patricia"

    End Sub

    You cannot use such a variable outside of its SubNameand the End Sublines.

    Global Variables

    A global variable is a variable declared outside of the SubName and the End Sub lines. Such avariable is usually dec lared in the top section of the file. Here is an example:

    Option Explicit

    Dim LastName As String

    Sub Exercise()

    End Sub

    After declaring a global variable, you can access it in the other areas of the file. Here is an example:

    Option Explicit

    Dim LastName As String

    Sub Exercise()

    Dim FirstName As String

    FirstName = "Patricia"

    LastName = "Katts"

    End Sub

    Although we declared our global variable inside of the file where it was used, you can also declare a

    global variable in a separate module to be able to use it in another module.

    The Access Level of a Global Variable

    Introduction

    When using a global variable, the Visual Basic language allows you to control its access level. The

    access level of a variable is a process of controlling how much access a section of code has on thevariable.

    Private Variables

    A variable is referred to as private if it can be accessed only by code from within the same file (the

    same module) where it is used. To declare such a variable, instead of Dim, you use the Privatekeyword. Here is an example:

    Option Explicit

    PrivateLastName As String

    Sub Exercise()

    Dim FirstName As String

    FirstName = "Patricia"

    LastName = "Katts"

    End Sub

    Remember that a private variable can be accessed by any code in the same module. In the nextlesson, we will learn how to create other sections of code.

    Public Variables

    A variable is referred to as public if it can be accessed by code either from within the same file (the

    same module) where it is declared or from code outside its module. To declare a public variable,

    instead of Dim, you use the Publickeyword. Here is an example:

    Option Explicit

    Private LastName As String

    PublicFullName As String

    Sub Exercise()

    Dim FirstName As String

    FirstName = "Patricia"

    LastName = "Katts"

    FullName = FirstName & " " & LastName

    End Sub

    As a reminder, a public variable is available to code inside and outside of its module. This means that

    you can create a module, declare a public variable in it, and access that variable in another file(module) where needed.

    A private variable is available inside its module but not outside its module. If you declare a private

    variable in a module and try accessing it in another module, you would receive an error:

    Module 1:

    Option Explicit

    Private FullName As String

  • 8/12/2019 MS. Excell VBA-#3, July 24, 2013

    10/10

    24/07/13 Microsoft Excel VBA: Variables and Data Types

    f i / b l/f d l /L 3 h 10/10

    Module 2:

    Option Explicit

    Private LastName As String

    Private FirstName As String

    Sub Exercise()

    FirstName = "Patricia"

    LastName = "Katts"

    FullName = FirstName & " " & LastName

    ActiveCell.FormulaR1C1 = FullName

    End Sub

    This would produce:

    Home Copyright 2008-2010 FunctionX, Inc.

    http://www.googleadservices.com/pagead/aclk?sa=L&ai=CRCS06U_vUeSVF4jOigfe-4D4BPuD29oD49-18Fna2R4QASDcj4ECUOToircEYOkCoAGvz8T-A8gBAqgDAcgD0QSqBJABT9CelJi_i2xEx7Pib2LuREDH7x4clkqJKCSRO16tWcio4X5XIMaS_qFDrbFGEC9mLbBCI5JtAZ2YReRTZ_XDLDQ6L5uPIdeqlpfTImY28nRUQh2pWrzY_RObjdTp6emSyGh_OlaywLJY0dj35XRD9KMGM8uZiv6CxEYV-63XHRzJuh1ZnIjlmawIB4uBnZitiAYBoAYCgAe5sLsB&num=1&cid=5GgVFfqTCv2WFym7vsWSTvK-&sig=AOD64_32JC9StvKWkxY0n1EQ__-AAHFhgQ&client=ca-pub-3968514660870014&adurl=http://www.tekscan.com/interface-load-gauge%3Futm_source%3Dgoogle%26utm_medium%3Dcpc%26utm_term%3Dload%2Bgage%26utm_content%3Dad9%26utm_campaign%3Dpressure%2Bdisplayhttp://www.functionx.com/vbaexcel/index.htmhttp://www.functionx.com/vbaexcel/index.htm