Variables

Top

Index

Declaring Variables - Variable Types
Data Type Storage Size
Boolean 2 bytes
Integer 2 bytes
Long 4 bytes
Double 8 bytes
Currency 8 bytes
Date 8 bytes
String 10 bytes + string length
Top

Index

Declaring Variables - Types Demo
declare variables using Dim
 
    Sub example
        Dim hi As String
        Dim dbl As Double
        Dim myDate As Date
    
        hi = "Hello World!"
        dbl = 634.23
        myDate = "4/3/2018" 
    End Sub
       
Top

Index

Calling a Procedure from Another
 
    Sub proc1()
        MsgBox "in proc1"
        Call proc2
        Call proc3("Hello World!")
        MsgBox "in proc1"
    End Sub

    Sub proc2()
        MsgBox "in proc2"
    End Sub

    Sub proc3(t)
        MsgBox t
    End Sub
    
Top

Index

Concatenation - Joining Two or More Strings
 
    Sub concat()
        myTxt1 = "Concat example : "
        myTxt2 = "Hello World!"
        myNum = 23
        MsgBox mtTxt1 & myTxt2
        MsgBox mtTxt1 + myTxt2
        MsgBox mtTxt1 & myNum
        ' next line generates a type mismatch error
        MsgBox mtTxt1 + myNum
    End Sub
    
Top

Index

Date Math Fun
a day is 1 unit
 
    Sub dateMath()
        myDate = Date
        MsgBox myDate
        myDate = myDate + 1
        MsgBox myDate
    End Sub
        
an hour is 1/24 of a day
 
    Sub timeMath()
        myTime = Now
        MsgBox myTime
        ' add one hour to the time
        myTime = myTime + (1 / 24)
        MsgBox myTime
    End Sub  
    
Top

Index

Public and Private Variables
in the macro below myVar1 is in global scope so it can be accessed by other modules
the private scope of myVar2 limits its visibility to the module it is in
     
    Public myVar1 As Double
    Private myVar2 As Double

    Sub proc1()
        MsgBox myVar1
        Call proc2
        MsgBox myVar1
    End Sub

    Sub proc2()
        myVar1 = 1234
    End Sub
    
Top

Index

Using Constants
constants can be private or public in scope
 
    Const myConst As String = "Hello World!"
    Sub proc()
        MsgBox myConst
    End Sub
    
Top

Index

Passing Variables to Another Procedure - ByVal and ByRef
 
    Sub callingSub()
        a = 10
        b = 20
        CalledSub1 a, b
        MsgBox a & ", " & b
        CalledSub2 a, b
        MsgBox a & ", " & b
    End Sub

    Sub CalledSub1(ByVal y, ByVal z)
        y = 100
        z = 200
    End Sub

    Sub CalledSub2(ByRef y, ByRef z)
        y = 100
        z = 200
    End Sub
    
Top

Index

Exercise 4
 
    Sub getDaysOld()
        Dim myDate As Date
        myDate = "12/31/1990" 

        myMsg = Date - myDate

        myHrs = myMsg * 24 'number of hours

        MsgBox "You are " & myMsg & " days old, " & myHrs & " total hrs old!"
    End Sub    
    
Top

Index

n4jvp.com