VBA Programming Part One
Our Dartmouth Legacy 10 INPUT "What is your name: "; U$ 20 PRINT "Hello "; U$ 25 REM 30 INPUT "How many stars do you want: "; N 35 S$ = "" 40 FOR I = 1 TO N 50 S$ = S$ + "*" 55 NEXT I 60 PRINT S$ 65 REM
Startup Excel and hit… Alt-F11
First things first: Getting Help
Getting More Help
Project Explorer Excel objects User Forms Code Modules
Properties Window Properties are an object's characteristics, e.g. a sheet's name.
Immediate Window
Using the Immediate Window
Try the Immediate Window MsgBox("Hello!") x = debug.Print x 'this is a comment x = WorksheetFunction.Sum(1,2) debug.Print x
Insert a module
Add some code Sub HelloWorld() MyName = InputBox("What is your name?") MsgBox ("Hi " + MyName) End Sub Type "HelloWorld" in the Immediate Window to run your program. Go back to Excel and run it from the Tools|Macro menu
Subroutines vs. Functions Both are procedures: A named sequence of statements executed as a unit. (MS) Functions return a value Subroutines don't
Procedures take arguments
Arguments are variables
But what are variables? "A named storage location that can contain data that can be modified during program execution." (MS) 1. Has name 2. Contains data 3. Can be modified
Convert Celsius to Fahrenheit Function Fahrenheit(Celsius) Fahrenheit = (Celsius * 1.8) + 32 End Function
Use the Function
Back to the Immediate Window x = 1 debug.Print x 1 x = 2 debug.Print x 2 'Set the value of x to 1 'Now set it to 2
Making Decisions
Decisions: If…Then Function VeryHot(Celsius) If (Celsius > 30) Then VeryHot = True Else VeryHot = False End If End Function
Which number is bigger? Function MyMax(x, y) If ( … ) Then … Else … End If End Function Remember: 'FunctionName = Result'
Which number is bigger? (Solution) Function MyMax(x, y) If ( x > y ) Then MyMax = x Else MyMax = y End If End Function
Loops: For…Next For Variable = BeginValue to EndValue do something with Variable Next Sub firstLoop() For x = 1 To 10 Debug.Print x Next End Sub
Example: Sum of 1…N Function SumToN(N) SumToN = 0 For x = 1 To N SumToN = SumToN + x Next End Function
TemperatureChart Create a sub called TemperatureChart Use For…Next to loop Celsius from 0 to 40 Use debug.print to output the result of converting Celsius to Fahrenheit using our function
TemperatureChart (Solution) Sub TemperatureChart() For Celsius = 0 To 40 Debug.Print Fahrenheit(Celsius) Next End Sub
What we have covered so far… The VBA environment Inserting a module Running a macro Writing a user-defined function Using the new function in Excel Variables If…Then…Else For…Next