vba programming part one. our dartmouth legacy 10 input "what is your name: "; u$ 20 print...
Post on 21-Dec-2015
214 views
TRANSCRIPT
VBA Programming
Part One
Our Dartmouth Legacy10 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 = 1 + 1 debug.Print x 'this is a comment x = WorksheetFunction.Sum(1,2) debug.Print x
Insert a module
Add some codeSub 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 name2. Contains data3. Can be modified
Convert Celsius to Fahrenheit
Function Fahrenheit(Celsius) Fahrenheit = (Celsius * 1.8) + 32End Function
Use the Function
Back to the Immediate Windowx = 1debug.Print x 1 x = 2debug.Print x 2
'Set the value of x to 1
'Now set it to 2
Making Decisions
Decisions: If…ThenFunction VeryHot(Celsius) If (Celsius > 30) Then VeryHot = True Else VeryHot = False End IfEnd Function
Which number is bigger?Function MyMax(x, y) If ( … ) Then … Else … End IfEnd Function
Remember: 'FunctionName = Result'
Which number is bigger? (Solution)Function MyMax(x, y) If ( x > y ) Then MyMax = x Else MyMax = y End IfEnd Function
Loops: For…NextFor Variable = BeginValue to EndValue
do something with VariableNext
Sub firstLoop() For x = 1 To 10 Debug.Print x NextEnd Sub
Example: Sum of 1…N
Function SumToN(N) SumToN = 0 For x = 1 To N SumToN = SumToN + x NextEnd 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) NextEnd 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