Presentation on theme: "ENGINEERING 160 Exit VBA Lessons: Class Introduction"— Presentation transcript:
1 ENGINEERING 160 Exit VBA Lessons: Class Introduction Algorithms and FlowchartsIntro to ProgrammingInput/OutputPart OnePart TwoControlling the FlowPart 1: Decisions and alternativesPart 2: LoopsOne Dimensional ArraysMulti-Dimensional ArraysFunctionsSubprograms as Subs or SubroutinesSubprograms with ArraysEngineering Problem Solving Lessons:Problem Presentation in EngineeringDimensions and UnitsEstimationAnalysis in DesignGraphing and Curve FittingPart OnePart TwoStatisticsSpreadsheets and MS ExcelEngineering EconomyStaticsExcel VBA ProgrammingCopyright,Iowa State UniversityExit
2 Introduction to Engineering 160 Originally authored by: Mark SobekAuthored for presentation by: Julie SandbergDate last updated: 8/9/01
3 Engineering 160(2) 1 hr. 50 min. lectures withlabs on PC’s
4 Open Labs: For information regarding open lab hours, Open labs are usually provided first in 2260 Hoover. Other labs may be opened as available and as needed.For information regarding open lab hours,Visit
5 Class Policies: Classroom procedures Programming proficiency score required (60% on exams)GradingInstructor’s office hours
6 ENGR 160 - Course Objectives To expose students to a wide variety of engineering problems similar to material they will study in greater depth later.To help students learn to translate verbal, written or graphical problems into mathematical models.To give students a perspective of engineering by introducing them to the art of making estimations and approximations and questioning the sensibility of numerical results.
7 More Course Objectives Engineering 160More Course ObjectivesTo help students develop an orderly process of presenting the calculations required in solving engineering problems so that others may readily understand their work.To prepare students to communicate results of their work through graphs, charts, etc.To prepare students for the process of solving engineering problems via a computer programming and use of a spreadsheet.Exit
8 Problem Presentation in Engineering Initially authored by: Mark SobekAuthored for presentation by: Julie SandbergDate last updated: 8/ 8/ 01
9 Steps in Problem Solving Recognize and understand the problem.Accumulate all the facts available: Determine all known and unknown variables.Make necessary assumptionsSelect an appropriate theory to solve the problem.Solve the problem.Verify and check the solution.
10 Guidelines for Problem Presentation (Word processing may be required. Some rulesapply only to handwritten work)1. Use engineering problems paper (plain side).2. Top heading of paper should be completed asfollows:3. Work should be in pencil. (except for computeroutput)Course No.PgDue DateNameProblem Nos.Tot
11 More Guidelines for Presentation: 4. Use clear, consistent, uniform lettering.5. Use correct spelling.6. Work must be easy to follow -- not crowded.7. Use a straight edge for line work.8. Use proper symbols for units.
12 Physical Problem Layout: Course No.1NameDue DateProblem Nos.2Problem Statement: State the problem to be solved.Include the problem number.Diagram: A diagram with all pertinent data (knownand unknown) should be shown. “One picture isworth a thousand words.”Assumptions: List all assumptions used in thesolution process.
13 Physical Problem Layout 2: Course No.2NameDue DateProblem Nos.2Theory: Present the theory used. If anequation must be derived, do it in the theory section.Reference all equations. Define all variables.Solution: Show all important steps inobtaining the solution.Discussion/Conclusion: Discuss the resultsobtained. Present your conclusions.
14 Physical Problem Layout 3: Engineering 1601Sobek, Mark1/21/01Example 12Problem Statement: Determine the volume and mass ofwater contained in the cylindrical water tank shown below.Diagram:Assume: Tank is full.2. Inside dimensions are given3. Water is at 50°F40.0 ftWater density at50°F is 1 kg/L20.0 ft
15 Physical Problem Layout 4: Engineering 1602Sobek, Mark1/21/01Example 12Theory: V = (/4)D2Hm = VWhere: V = Tank volume LD = Tank diameter mH = Tank height mm = Water mass kg = Water density kg/LSolution:V = (/4)(40 ft)2 (20 ft) = (105) ft3= (105) ( L/ft3)= 7.12 (105) Lm = (1 kg/L)(7.12 (105) L)= 7.12 (105) kg
16 Physical Problem Layout 5: Engineering 16011/21/01Sobek, MarkExample 23Problem Statement: Determine the length of side UT of theland plot shown below. Evaluate the area.Diagram:S90 mT120 m115°100°RObstruction130 mUAssume: 1. The plot of land is planar
17 Physical Problem Layout 6: Engineering 1602Sobek, Mark1/21/01Example 23Theory:Apply the Law of Cosines to RST:RT = [RS2 + ST2 - 2(RS)(ST)cos(RST)]1/2Apply the Law of Sines: = sin-1[(RU/RT)sin(RUT)] = 180º-RUT - UT = (RT) sin()/sin(RUT)Area RSTU = AreaRST+ Area RTU= (1/2)(RS)(ST)sin(RST)+(1/2)(RU)(UT)sin(RUT)
19 Dimensions and Units Lecture written by: Dr. James Hilliard Authored for presentation by: Julie SandbergDate last updated: 6/16/98
20 Example: Consider the following mechanical system: ZMotionPathVelocityMassYXSystem Description - In order to describe the abovesystem, one needs to define a set of physical parameters. Mass Velocity Etc. Time Momentum Length Energy
21 Definitions: Dimensions - The set of physical parameters used to define the state of asystem.Units - A standard quantity that allows oneto establish a value for a dimension.Physical QuantityUnitA = (N) (U)Numerical Value
22 Fundamental and Derived Dimensions Fundamental Dimension - A dimension that cannotbe derived from other dimensions.Derived Dimension - A dimension that can be defined bysome mathematical combination of fundamentaldimensions.
23 Example: V = L / T Let length (L) and time (T) be fundamental dimensions. Let velocity (V) be anotherdimension used to describe a system state. Arelationship exists as follows:V = L / TTherefore, velocity is a derived dimension!
24 Dimensional SystemDimensional System - The smallest set of fundamentaldimensions that can be used for a complete study of afield of science.Examples: (Systems used in Mechanics)“Absolute System”-Fundamental dimensions arelength, mass, time.“Gravitational System”length, force, time.
25 Note: Note: Force and Mass are related by Newton’s Law: F = (M)(A) Where:F = Force (N)M = Mass (kg)A = Acceleration of gravity (m/s2)In U.S. units:F = Force (lb)M = Mass (slug)A = Acceleration of gravity (ft/s2)
26 The new common system being adopted is the The SI Metric System:During the past several years, many types of unit systemshave been in use. Generally, they were variations of twotypes:(1) British System(2) MKS MetricThe new common system being adopted is theSI Metric System!
27 Unit Classes The SI metric system contains 3 classes of units: (1) Base units(2) Supplementary Units(3) Derived Units
28 Base Units: Quantity Name Symbol Length Mass Time Electric Current ThermodynamicTemperatureAmount of aSubstanceLuminousIntensityMeterKilogramSecondAmpereKelvinMoleCandelamkgsAKmolcd
29 Supplementary Units: Quantity Name Symbol Plane angle Solid angle RadianSteradianradsr
30 Example:The density of water at 50ºF is about 1.94 slug/ft3. Determine thevolume of a 50.0 ft-diameter cylindrical tank with a height of 35.0 ft.Then calculate the mass of water contained if the tank is full. Expressvolume in cubic meters and mass in kilograms.Vol = R2 H= (25.0 ft) ft ( m)3ft3= 1946 = 1.95 x 103 m3Mass = (Vol)(Density)= (25.0 ft) ft slug kgft3 slug= 1.95 x 106 kg50.0 ft35.0 ft
31 Numbers & Errors Types Of Errors: * Systematic (Bias) * Accidental (Statistical)Note: Precision, which is a measure of error, isproperly conveyed numerically by usingappropriate significant digits.
32 Significant Figures writing a number, except those used to define only Significant figures are figures (digits) used inwriting a number, except those used to define onlythe decimal location such as:2000, 200, , ETC.Or those zeros which do not have non-zero digitson their left.0.0015, , ETC.
34 Rounding NumbersIf the first digit discarded is < 5, leave the last digit kept unchanged.If the first digit discarded is > = 5, increase the last digit kept by 1.
35 Rules for Addition (Subtraction) The answer should show significant digits only as far to the right as is seen in the least precise number.Find the least precise number.Add (Subtract) the numbers.Round the answer such that the last significant digit is no farther right than that of the least precise number.
37 Rules for Multiplication (Division) The product or quotient shall contain no moresignificant digits than are contained in the numberwith the fewest significant digits initially.Example:(27.08)/(19) == 1.4
38 Example (Proper Use of Significant Figures) Engineering 160Example (Proper Use of Significant Figures)Convert miles to kilometers:10.00 miles kmmile= kmThus, the final answer (16.09 km) contains4 significant figures just like the miles did.Exit
39 Estimation Lecture written by: Dr. James Hilliard Authored for presentation by: Julie SandbergDate last updated: 6/ 18/ 98
40 Estimation Engineers continually make estimations. Calculated results are always suspect until thereasonableness of the answer is verified by estimation.Much embarrassment can be avoided by checkingcalculated results with a quick estimate.
41 Basis of Estimation The estimate is directly influenced by: A. Time availableB. Physical circumstances such as:1. Reference material at hand2. Access to a phone3. Computational equipment available
42 Estimates and Engineers The soundness of an engineer’s judgement will betested in many planning sessions.Estimates often decide which plans to explore inmore depth and detail.Experience, logic, and communication skills willdetermine if your voice is heard.
43 Good Estimation Techniques: Good estimating technique can be learned.A. Break the problem into manageable pieces.B. Clearly identify your assumptions.C. Structure your logic so that you caneasily explain and defend it.D. Further refinement of your estimate should bestraightforward and easy to implement.
44 Estimation Format Example Engineering 1601Sobek, MarkExample2Problem Statement: Estimate the volume of your pencil incubic mmAssumptions (A) Cylindrical shapeEstimates(A) 5 inches in length(B) inches in diameter
46 Analysis in Design Lecture written by: Dr. James Hilliard Authored for presentation by: Julie SandbergDate last updated: 6/ 18/ 98
47 Analysis in DesignA design must be analyzed in detail to be certain thatexpectations are met.The analysis involves calculating the response of thedesign at many operating points.At every operating point, the same calculations aremade and hence the term was developed:Repeated Analysis...
48 Repeated Analysis Repeated analysis is an excellent application for computers.Computer routines can loop many times per second andwith each loop, the solution at yet another operatingpoint is obtained.
49 Repeated Analysis etc.Since the computer can do the hard labor so quickly,many variations of the design can be tried - leading tooptimization.Computer output must normally be graphical in order toallow a quick grasp of the “blizzard” of numericalresults.
51 Example cont. Free Body Diagram Governing Equations: 1. ß = ARCTAN[(L sin - 2H)/L cos ]2. Ax = T cos ß3. Ay = T sin ß + Mg4. A = (Ax2 + Ay2)1/25. T = (2 Mg cos )/(cos ß sin - sin ß cos )ßMgTLHAxAy
52 Table of Values (Degrees) T (Newtons) A (Newtons) 10 20 30 40 50 60 7080495474461638427462394030362702335145313294299105483056463994449397433850419967408359399590394098
53 Crane Data Graph Exit BOOM ANGLE (degrees) 500000 450000 A 400000 T Engineering 160Crane Data GraphPIN&CABLEOD(N)500000450000A400000T3500003000002500001020304050607080BOOM ANGLE (degrees)Exit
54 Graphing and Curve Fitting Part One Lecture written by: Prof. Martha SelbyAuthored for presentation by: Julie SandbergDate last updated: 8/ 06/ 07
55 Representation of Technical Data Experimental Process Steps:Collecting dataRecording and presenting dataTabular formGraphical formData analysisIdentification of equation showing functional relationships
56 Steps in the Proper Construction of a Graph 1. Select proper type of graph paperA. Uniform grid - Rectilinear: i.e., 20 lines/inch10 lines/cmB. Non-uniform grid - Log-log (#of cycles/axis?)Semi-log
57 Steps in the Proper Construction of a Graph 2. Choose proper location of axesA. Place axes inside the edge of the printed gridB. Plot should use as much of the grid as possible,consistent with good scale rules.Ordinate, y axisDependent variableAbscissa, x axisIndependent variable
58 Steps in the Proper Construction of a Graph 3. Calibrate the axes:Assign numerical values to the graduationsGraduation1020Calibration
59 Steps in the Proper Construction of a Graph Follow the 1, 2 5 ruleOn a uniform scale the value of the smallest divisionmust be 1, 2, or 5x10 to some power(i.e. 1, 10, 0.1, 200, 0.02, 5, 50)Examples:Right!2468Wrong!2468
60 Steps in the Proper Construction of a Graph Log scale calibration: since log cycles are based onpowers of 10 each cycle is printed with values 1 to 10.You need to only decide what power of 10 to apply to thefirst cycle, then each cycle goes up by one power of 10.There can not be a value of zero since log0 is not defined.
61 Steps in the Proper Construction of a Graph 4. Label axesInclude: Name of the variable, the symbol, the unite.g. Time, t, s5. Plot points: Use a symbol around the data points;Lines don’t penetrate the symbols:- OR -
62 Steps in the Proper Construction of a Graph 6. Draw curves3 categories of data:ObservedTheoreticalExperimentalyyyxxx
63 Steps in the Proper Construction of a Graph Engineering 160Add plot title andkey to identify curvesif necessaryExit
65 Graphing and Curve Fitting Part Two Lecture written by: Prof. Martha SelbyAuthored for presentation by: Julie SandbergDate last updated: 6/ 23/ 98
66 Graphical Analysis Linear Function - Exponential Function - Plot as a straight line on uniform grid (rectilinear) paperY = mx + bExponential Function -Plot as straight line on semi log paperY = bemx or ln Y = mx + ln bPower Function -Plot as straight line on log-log paperY = bxm or log Y = m log x + log bln Y = m ln x + ln b
67 Curve Fitting MethodsTwo methods for arriving at the “best-fit” straightline will be considered this semester:1. Method of selected points2. Method of least squares - linearregression (Discussed later - Chap. 8)
68 Method of Selected Points Plot data on the correct graph paper.Draw a straight line by visually selecting a line that goes through as many points as possible and has about the same number of points on both sides of the line.Choose two points on line (not 2 of the data points).
69 Method of Selected Points: Substitute points into equation and solve for m & bY1 = mX1 + bY2 = mX2 + b
70 Method of Selected Points for Power Functions 1. Plot data on log - log paper.2. Draw the “best” line.3. Select 2 points off the line.Point A (X1,Y1) Point B (X2, Y2)Power Function: Y = bxmLog form: log Y = m log x + log b (could use ln or log in equation)Solve: log Y1 = m log X1 + log blog Y2 = m log X2 + log bFind m and b(NOT log b)
71 Method of Selected Points for Exponential Functions Engineering 160Method of Selected Points for Exponential FunctionsUse the same procedure for Exponential FunctionsY = bemxLog form: ln Y = mx + ln b(NOTE natural logs)Exit
72 Statistics Lecture written by: Dr. Larry Genalo Authored for presentation by: Julie SandbergDate last updated: 8/ 8/ 01
73 Statistics Statistics - parameters calculated from sample observations (usually engineers deal withsamples rather than the total population).Measures of AVERAGE (Central Tendency)MODE -- The most common value in sample.MEDIAN -- “Middle” value in the sample.MEAN -- Arithmetic average = X =NXiNi = 1
74 Variation Variance = S2 = Measures of Variation (scatter, dispersal) about the mean:N(Xi - X)2Variance = S2 =i=1N - 1Standard Deviation = S =S2Note: this equation for variance (using N-1) is used for a small sampleof a population
75 Alternative Deviation Equation An alternative equation to find the standarddeviation is the following:Standard Deviation = S =N(Xi2) - (Xi)2N (N-1)
76 Examplei123456Xi926374637878Modes = 63 and 78Median = (78+74) = 762Mean = X = ( ) = 74.676Standard Deviation = S = ( ) - ( ) = 10.91(using the alternate equation) (5)Variance = S2 = ( )2 = 119.1
77 Example 2i123...48Xi859372...5HistogramFreqof Occur.GradeClass15108131540 - 59Frequency5Upper limit of grade ranges
78 Frequency Distribution This can lead to a Continuous Distribution such as:X - SXX + SThis is an example of a theoretical distribution called theNormal Distribution or a“Bell-shaped” curve.This is used when grading “on a curve” and also appliesto many natural phenomena.
79 Curve Fitting Given a set of data points “model” them with a curve which approximates their behavior. We’ll look onlyat a straight line fit: Linear Regression by themethod of Least Squares.
80 Curve Fitting Problem Y What straight line is “best”? X The problem: We know that a straight line has the form:Y = mX + bWhat values of m and b are the “best”?
81 Curve Fitting Solution YpY’pYXpX(Xp, Yp) Real data pointY’p = mXp + b“Miss distance”Yp - Y’p = Yp - (mXp + b)
82 Curve Fitting Solution 2 Now calculate the sum of the squares of all “misses”Sum = (Y1 - (mX1 + b))2 + (Y2 - (mX2 + b))(YN - (mXN + b))2Note: All Xi and Yi are known.Calculus problem: Select m and b to minimize sum.
83 Curve Fitting Solution 3 Calculating partial derivatives (Pardon?), settingthem equal to zero and solving.
84 Common Concern A Concern: Given any set of data points, we can find m and b. When is it a good idea to modelwith a straight line??
86 Note: An alternate equation for Alternative RNote: An alternate equation forR is found as shown here...n (xiyi) - (xi)(yi)R =n(xi2) - (xi)2n(yi2) - (yi)2
87 Suggestions: Anytime you do a linear regression (or other types of curve-fitting) you should check the correlationcoefficient (or other goodness-of-fit parameters)Is R = 0.9 good enough?How about R = 0.8? 0.7?Deciding if R is “good enough” is an interpretive skilldeveloped through experience. We can say:If R = 0.8, then 64% of the variance in the dependentvariable is explainable by the variance in the independentvariable. Note: R2 = 0.64
88 Nonlinear Graphs “Patterned” data not following a straight line? Power - Model with a curved line- Transform to a straight line modelPowerCurve
89 Nonlinear Graphs 2 Exit Then, V = bTm logV = log b + m log T Engineering 160Nonlinear Graphs 2Then,V = bTm logV = log b + m log Ti.e., Let Y = log V and X = log TNow do a linear regression on the variables log Tand log V. Note that the intercept derived islog b (NOT b).Exit
90 Spreadsheets and MS Excel Part One Lecture written by: Dr. Larry GenaloAuthored for presentation by: Julie SandbergDate last updated: 6/ 24/ 98
93 To enter data using MS Excel, type the information in the formula bar.
94 Numerical Data Numerical Data to be used in calculations can be entered into the cells.
95 Entering Numeric Data1) Data being entered showsboth in the formula barand in the active cell.
96 Entering Numerical Data 2) Depress the check mark orpush either the Enter key or anarrow key to complete enteringthe data.
97 Entering Numeric Data3) Use either the mouse orthe arrow keys to navigateto the next cell in whichyou wish to enter data.
98 TextText can be entered to createrow and column headingswithin the spreadsheet.
99 Entering TextTo enter text, just type the text inthe formula bar and enter it as you wouldfor numbers.
100 Entering TextTo enter numerical values as text,type a single quote (‘) followed by thenumber.
101 Formulas In Excel, formulas can be entered in cells to represent numerical values. There are two basictypes of formulas:1. Numeric Formulas2. Reference FormulasTo enter a formula, always begin with an equalssign (=), then proceed with the formula.
102 Numeric Formulas A numeric formula in Excel is a mathematical expression that can be simplified to a single valueindependent of the values in any other cell.
103 Numeric FormulasTo enter numeric formulas, enter theformula in the formula bar. When it is entered,the formula will still be visible in the formulabar while the actual value will appear in the cell.
104 Reference Formulas A Reference formula in Excel is a mathematical expression that contains references to othercells as variables.
105 References In order to enter formulas in MS Excel, two basic types of cell references may be used.1. Absolute references are used to denote one specificcell within the spreadsheet. In MS Excel, these aredenoted by putting a dollar sign ($) in front of both thecolumn and row markers. For example, the cell A1would be denoted as $A$1 in absolute reference.2. Relative references are used to find cells relative tothe formula cell. In MS Excel, they are denoted byusing the column and row markers as they appear.For example, the cell A1 would be denoted as A1 inrelative reference.
106 Reference FormulasTo enter reference formulas, enter the formula in theformula bar using references to cells containing data.When the formula is entered, the answer will appear inthe cell, while the formula remains in the formula bar.
107 Copying Formulas To copy a formula from an active cell, find the Copy command under the Edit menu. Highlightthe area where the formula is to be copied. Findthe Paste command under the Edit menu or ifyou wish to copy across a row or down a columnselect Edit-Fill after selecting the row or column.NOTE: Absolute and relative references willcause different results when copied, asdemonstrated by the following examples.
108 Absolute ReferenceAssume the following data has been entered incolumns A and B. Given that the formula forD1 is =$A$1+$B$4, note what happens when itis copied to cells D2-D4.
109 Assume the same data has been entered in When the formula was copied,its references changed relativeto the cell it was pasted in.Relative ReferenceAssume the same data has been entered incolumns A and B. Given that the formulafor D1 is =A1+B1, note what happenswhen it is copied to cells D2-D4.
110 Function A function is a prewritten formula that performs an operation on givenvalues and returns a value or values.It can be used alone or as a buildingblock in a formula.
111 Examples of MS Excel functions ACOS( ) - arccosine LN( ) - natural logASIN( ) - arcsine LOG( ) - log, base 10ATAN( ) - arctangent SIN( ) - sineAVERAGE( ) - average STDEV( ) - standard deviationCOS( ) - cosine TAN( ) - tangent
112 Using FunctionsWhen you have reached a point in aformula where you wish to insert afunction, you can either enter thefunction name and arguments or youcan use the Function Wizard.
113 Using FunctionsThe Function Wizard is a useful series of dialogueboxes that allow you to choose the function youdesire from a complete list of Excel Functions andtheir descriptions. To access the Function Wizard,just click on the function key in the formula bar.
114 Function Wizard Step 1 1) Choose the desired Function category Function Name.(note the descriptions andform at the bottom)3) Click OK to move on.
115 Function Wizard Step 21) Enter the desirednumerical value(s)or cell reference(s)as arguments.2) Click the OK key
116 Engineering 160YES! We have a value for Pi.Exit
117 Spreadsheets and MS Excel Part Two Lecture written by: Dr. Larry GenaloAuthored for presentation by: Julie SandbergDate last updated: 6/ 25/ 98
118 Graphing with MS Excel Creating graphs with MS Excel is a useful way to get a visualrepresentation of collected data.
119 Preparing Data There are two things you can do to prepare your data that can make it much easier to create a graph:Make sure the column containing your independent variable is to the left.This can be done by highlighting a column, cutting, and pasting.Make sure your values for your independent variable are in increasing order.This can be done by highlighting all data and choosing Sort from the Data pull-down menu. Make sure you are sorting by your independent variable!
120 GraphingAfter you have prepared your data, Excelmakes it simple to construct a graph.First, highlight your data. Then, click on theChart Wizard icon.
121 GraphingThe Chart Wizard series of four dialogueboxes will appear prompting you for informationabout how you want your graph constructed.
122 Example The following sequence of slides show how a chart might be constructed fromthe given data.
132 Editing a Finished Graph Engineering 160Editing a Finished GraphAfter a graph has been constructed, itcan be edited by clicking on its variousparts or by using the chart toolbar.Exit
133 Engineering Economy Lecture written by: Dr. Larry Genalo Authored for presentation by: Julie SandbergDate last updated: 8/ 8/ 01
134 Engineering Economy P = Present Sum (Cash Flow) The following variables will be used throughout the presentationP = Present Sum (Cash Flow)F = Future Sum (Cash Flow)N = Number of Time PeriodsI = Interest RateA = Equal Cash Flow Each Time Period
135 Simple Interest Equation: F = P + N I P = P (1 + N I ) Example: If $ was deposited at 6% yearlyinterest, your account would have these balances aftereach year:Year Balance
136 Compound Interest Equation: F = P (1+I)N “Interest on the Accrued Interest”Equation: F = P (1+I)NExample: If $ was deposited at 6% interest andcompounded annually, your account would have thesebalances after each year:Year Balance Equation1234N100.00106.00112.36119.10126.25100 (1.06)NPP(1+I)1P(1+I)2P(1+I)3P(1+I)4P(1+I)N...
137 Compound Interest Time Line “Forward Time”Example: If you deposit $ today at 7% interestcompounded annually, what will be the balance in 3 years?Solution: F = Future Value = P(1+I)N= $ ( )3 = $
138 Compound Interest Time Line “Backward Time”Example: If $ is needed in 3 years, how much moneyshould be deposited today, assuming 7% interest compoundedyearly?Solution: P = Present Value = F(1+I)-N= $ (1+0.07)-3 = $
139 Compound Interest Time Line “Backward Time”Example: If $ is needed in 3 years, how much moneyshould be deposited today, assuming 7% yearly interestcompounded quarterly?Solution: P = Present Value = F (1 + I/4)-N= $ ( /4)-12 = $
140 Compound Interest Time Line “Backward Time”Example: If $ is needed in 3 years, how much moneyshould be deposited today, assuming 7% yearly interestcompounded quarterly?Solution: P = Present Value = F (1 + I/4)-N= $ (1+0.07/4)-12 = $Compare: The answer where interest was compoundedquarterly is less than the previous answer where interestwas compounded yearly:Solution: P = Present Value = F (1 + I)-N= $ ( )-3 = $
141 Tips for Doing Problems When doing engineering economy problems, make sure:“Time frames” matchIf one period equals one quarter, then the interest rate should be quarterly and compounded quarterly. For example, if a yearly interest rate is given but interest is compounded monthly, divide the interest rate by 12Answer is reasonableAnswer is rounded to the nearest penny
142 Sinking FundDefinition: A sinking fund differs from compound interestin that we now have uniform payments over timein addition to the compounded interest.Solution: F = A + A(1+I)1 + A(1+I) A(1+I)N-1(1+I)N - 1F = AI
143 Sinking Fund Time Line Example #1 Example: If you deposit $50 per month into an account thatpays 6% interest, compounded monthly, for 2 years, howmuch is in the account immediately after the last deposit?( )24 - 10.0612Solution: F = Future Value = $50= $( )0.0612
144 Sinking Fund Time Line Example #1 Example: If you deposit $50 per month into an account thatpays 6% interest, compounded monthly, for 2 years, howmuch is in the account immediately after the last deposit?Please Note: Yearly interest in the equation is divided by 12since payments are on a per-month basis.Also Note: There are 24 payments, not 23 months.( )24 - 10.0612Solution: F = Future Value = $50= $( )0.0612
145 Sinking Fund Time Line Example: Which is of more value to receive: (a) $8000 today or(b) 5 annual payments of $2000, beginning in 1 year?Assume 8% interest compounded annually.
147 Sinking Fund Time Line Example #2 Time Line: Solution: First, we find the future value of the money:F = Future Value = $2000= $( )5 - 10.08
148 Sinking Fund Time Line Example #2 Time Line: Solution: Then, we find the present value of the money:PB = Present Value = F (1+I)-N = $ (1.08)-5= $Note: Since PA = $8000 > PB = $ , select plan A.
149 Sinking Fund Time Line Example #3 Example 2: Which is of more value to receive:(a) $8000 today or(b) 5 annual payments of $2000, beginning in 1 year?Assume 8% interest compounded annually.Example 3: What if plan B started today?(c) 5 annual payments of $2000, beginning today?Assume 8% interest compounded annually
150 Sinking Fund Time LineExample #3Old Time Line:New Time Line:
151 Sinking Fund Time Line Example #3 New Time Line: Solution: First, we find the future value of the money:F = Future Value = $2000= $(1+0.08)5 - 10.08
152 Sinking Fund Time Line Example #3 New Time Line: Solution: Then, we find the present value of the money:PB = Present Value = F(1+I)-N = $ (1.08)-4= $Note: Since PA = $8000 < PC = $ , select plan C
153 Annuity Note: Follow the algebraic steps used to find the present value of a sinking fund. This is the formula for an annuity.(1+I)N - 1ISolution: F = A& P = F(1+I)-NTherefore: P = A(1+I)N - 1I(1+I)N
154 Annuity Application: The first application of the annuity formula is to find the present value of a sinking fund. The second isusing the formula in situations like the following example.Example: You borrow $15,000 to buy a car. If you repaythe loan with 48 monthly installments at 7% annualinterest, what is the amount of each payment?
155 Annuity Example: You borrow $15,000 to buy a car. If you repay the loan with 48 monthly installments at 7% annual interest,what is the amount of each payment?$1500045464748(1+ )48 - 1(1+ )480.0712Solution: = AA = $359.190.07120.0712
156 SummaryCompound InterestEquation:F = P (1+I)NTime Line:
159 Amortization TableDefinition: An amortization table is used to track monthlypayments when repaying a loan.Example: If you take out a loan for $70,000 to be paidback in 30 years at a fixed yearly interest rate of 10.5%,what will be the amount of the monthly payment? Alsocreate an amortization table for the first 12 months. [Takenfrom a table in an article by the Des Moines Register.]( )( )3600.10512Solution: = A0.105120.10512A = $ (monthly payment)
161 Amortization Table Table: AI = $70000 (0.105 / 12) AI = $612.50 PaymentNumberMonthlyPaymentAmount forInterestAmount forPrincipalCurrentBalanceAmount for Interest isfound by multiplying theprevious Current Balanceby the monthly interest rate:AI = $70000 (0.105 / 12)AI = $612.50
162 Amortization Table Table: AP = $640.32 - $612.50 AP = $27.82 PaymentNumberMonthlyPaymentAmount forInterestAmount forPrincipalCurrentBalanceAmount for Principal isfound by subtracting theAmount for Interest fromthe Monthly Payment:AP = $ $612.50AP = $27.82
163 Amortization Table Exit Table: CB = $70000 - $27.82 CB = $69972.18 Engineering 160Table:PaymentNumberMonthlyPaymentAmount forInterestAmount forPrincipalCurrentBalanceCurrent Balance is foundby subtracting the Amountfor Principal from theprevious Current Balance:CB = $ $27.82CB = $Exit
164 Statics Lecture written by: Prof. Martha Selby Authored for presentation by: Julie SandbergDate last updated: 8/ 8/ 01
165 Mechanics The study of forces acting on bodies. 3 Branches of Mechanics:-Statics-Dynamics-Strength of Materials
166 Statics Force The study of rigid bodies that are in equilibrium. A “push” or “pull” exerted by one body on another,such as:- a person pushing on a wall- gravity pulling on a person
167 Scalar / Vector Scalar Vector A quantity possessing only a magnitude. - mass, length, timeVectorA quantity that has both a magnitude and direction.- velocity, force
168 Force Force is a vector quantity, therefore a force is completely described by:1) magnitude2) direction3) point of application50 NA30º
169 Vectors Types of vectors used in statics: Concurrent vectors have Coplanar vectors liein the same plane.Concurrent vectors havelines of action that passthrough the same point.Colinear vectors act along the same line of action.
171 Resolution of forces into components The net effect of a number of forces on one point can bethe same as the effect of one force.Fx = F cos Fy = F sin = tan-1 (Fy/Fx)F = (Fx2 + Fy2)1/2FFyFyFx(Fx)2 + (Fy)2 = F
172 Finding Resultant Forces To find a resultant force from a system of forces:1) Resolve each force into X & Y components.2) Add all X components.Rx = Fx1 + Fx2 + Fx3) Add all Y components.Ry = Fy1 + Fy2 + Fy4) Find resultant force, RR = (Rx2 + Ry2)1/2 = tan-1(Ry/Rx)RRyRx
173 Example F1y = 95.0 sin 30.0 = 47.5 N F1x = 95.0 cos 30.0 = 82.3 N F1 = 95.0 NF1yF2 = 62.0 N30.0°F2y15.0°F2xF1xF1x = 95.0 cos 30.0 = NF2x = 62.0 cos 15.0 = NSum of Fx = NF1y = 95.0 sin 30.0 = 47.5 NF2y = 62.0 sin 15.0 = 16.1 NSum of Fy = 63.6 N
174 Example 2 F1y = 95.0 sin 30.0 = 47.5 N F1x = 95.0 cos 30.0 = 82.3 N Sum of Fx = NF1y = 95.0 sin 30.0 = 47.5 NF2y = 62.0 sin 15.0 = 16.1 NSum of Fy = NFy = 63.6 NF = ?F = ( )1/2 = 67.4 N = tan-1(63.6/22.4) = 71.3° = ?Fx = 22.4 N
175 A Moment The tendency of a force to cause rotation about a point. Moment = ( force magnitude ) ( )Perpendicular distance from force’sline of action to the point.AAF = 10.0 NARB = 1.5 mRA = 2.0 mBMB = 10.0 N (1.5 m) = 15 Nm, direction is clockwise, CWMA = 10.0 N (2.0 m) = 20 Nm, direction is counterclockwise, CCW
176 Free Body DiagramsA free body diagram is a sketch of the body and all theforces acting on it.3 steps in drawing a free body diagram.1) Isolate the body, remove all supports and connectors.2) Identify all external forces acting on the body.3) Make a sketch of the body, showing all forces acting on it.
177 Inclined Plane (no friction) Support removedForce normal to theplane
178 A tension force along the Cable, Rope, or ChainConnector removedA tension force along thecable, away from thebody.
179 Roller or Simple Support Support removedForce perpendicular to the surface on which the rollercould roll
180 force are shown. The direction of the component forces are assumed and Pin or HingePin removedFxFyResultant force is at some unknown angle, so the X & Y components of theforce are shown. The direction of the component forces are assumed andmay be wrong.
181 Equilibrium A body is in equilibrium if the sum of all the external forces and momentsacting on the body are zero.1) Fx = 02) Fy = 03) M = 0 (about any point)
182 Steps in solving a statics problem. Draw a free body diagramChoose a reference frame. Orient the X & Y axes(most often X is chosen in the horizontal direction and Y is chosen in the vertical direction.)Choose a convenient point to calculate moments around.(most often this will be at the pin connection)Apply the 3 equilibrium equations and solve for the unknowns.
183 Example Problem Two children balance a see-saw in horizontal equilibrium. One weighs 80 pounds, and the otherweighs 60 pounds and is sitting 4 ft from the fulcrum.Find the force the fulcrum applies to the beam andthe distance from the fulcrum to the 80 lb child.(Neglect the mass of the see-saw.)Diagram80 lbs60 lbsX ft4 ft
184 Example Free Body Diagram F Solution Fx = 0 = No X forces. 80 lbs60 lbs+xX ft4 ftFSolutionFx = 0 = No X forces.Fy = 0 = F F = 140 lbsMfulcrum = 0 = 80 * X - 60 * X = 3 ft+
185 Example 2 Neglect mass of beam. Free Body Diagram 2.00 m 70.0 kg C D 60.0º2.50 m1.00 mFree Body Diagram2.00 m70.0 (9.81)D cos(60.0º)YCxCyXD sin(60.0º)2.50 m1.00 m
187 Example 3 Free Body Diagram A 150 N B C 300 N D 30.0º 150 N Ay Ax Y B Beam Length = 8.00 mAB = 2.00 mBC = 2.00 mCD = 4.00 mNeglect mass of beamA150 NBC300 ND30.0ºFree Body Diagram150 NAyAxYBAy = 300 cos 30.0Ax = 300 sin 30.0 = 30.0ºXDxDy
188 Example 3 Solution Exit Fx = 0 = -Dx + 300 sin(30.0) Engineering 160Example 3 SolutionFx = 0 = -Dx sin(30.0)Fy = 0 = Dy B cos(30.0)MD = 0 = 150(4.00) - B(6.00) + (300 cos(30.0))(8.00)B = 446 NDx = 150 NDy = N (negative sign implies the wrong direction was assumed)Dx = ?D = ?DyOR: 30.0º º = 16.3ºD = ( )1/2 = N = tan-1(36.6/150) = 13.7ºDExit
189 Algorithms and Flowcharts Lecture written by: Prof. Martha SelbyAuthored for presentation by: Julie SandbergDate last updated: 6/ 7/ 98
190 FLOWCHARTING Preparation for Programming Remember, a computer is only aproblem-solving tool!(one of the many different tools engineers use in solving problems)
191 Engineering Method of Problem Solving: 1) Recognize and understand the problem2) Accumulate facts3) Select appropriate theory4) Make necessary assumptions5) Solve the problem6) Verify results
192 Performing this step may involve a computer Engineering Method of Problem Solving:1) …………2) …………3) …………4) …………5) Solve the problemPerforming this step mayinvolve a computer6)…………
193 The 5 steps in using a computer as a problem - solving tool. a) Develop an Algorithm and a Flowchartb) Write the program in a computer language. (i.e.VBA, C)c) Enter the program into the computer.d) Test and debug the programe) Run the program, input data, and get the results from the computer.
194 5) Solve the problem a) Develop an Algorithm and a Flowchart An Algorithm is just a detailed sequence of simple steps that are needed to solve a problem.A Flowchart is a graphical representation of an algorithm
195 Flowchart Symbols Of the many symbols available, these 6 Basic Symbols will be used most:Question, Decision(Use in Branching)Start / StopConnector(connect one part of theflowchart to another)Input / OutputComments,Explanations,DefinitionsProcess,Instruction
196 2 Additional Symbols Related to more advanced programming Preparation (may be used with “counted loops”)Refers to Separate Flowchart(“Subprograms” are shown in separate flowcharts)
197 Flowchart Examples A simple sequential structure: Given the radius and STARTEnter Rand HR = Radius of cylinderH = Height of cylinderA simplesequentialstructure:V = Volume ofcylinderV= R2HGiven the radius andheight for a cylinder,find the volume.OutputR, H, VSTOP
198 Other Flowchart Examples Use to determine what form to use to fileFederal Income Tax ReturnStartNOAre you single?YESNOUnder age 65?YESClaimdependents?YESNONOTaxable income< 50,000?YESCan use Form1040EZMust use 1040Aor 1040Stop
199 Repetition / Looping Structure STARTInput a temperature inFahrenheit, F, and convertto Celsius, CEnter FC =5/9(F-32)OutputF, CYESAnotherValue?NOSTOP
200 More Repetition / Looping Structures Engineering 160StartCalculate the average from 25 exam scoresSum = Total sum of exam scoresC = Variable that keeps track of thenumber of exams addedSum = 0C = 0Enter ExamScore, SSum =Sum+SC = C+1NOIs C =25?YESAverage =Sum / 25OutputAverageStopExit
201 Introduction to Programming Concepts Using VBA Lecture written by: Prof. Martha SelbyUpdated for presentation by: Emily VereenDate last updated: Summer 2003
202 What is a Computer Language? A computer language consists of system of rules for writing a computer program.A program, or code, is set of instructions, called statements, arranged sequentially to tell a computer how to perform, or execute, the solution to a problem.Languages are developed for many reasons, ranging from programming operating systems to drawing graphical images, communicating on the Internet, and solving complex mathematical problems.
203 What’s VBA?VBA (Visual Basic for Applications) is a subset of Visual Basic ( VB )VB &VBA are modern, complete and very powerful languages (on par with Fortran and C)VBA has been included in the Microsoft Office Suite since Office 97VBA is designed for customizing software applications, however :In ENG 160, VBA will be used (within Word and Excel) to learn essential programming concepts and write programs to solve problems
204 How to Begin? The applications (Word or Excel) come with a programming environment (the IDE or Integrated Development Environment),which is a special place to write, edit and run VBATo create VBA programs (called macros), access the IDE:1) Open Word or Excel ) Access the Developer Tab→ Macros3) Name your Macro: names must start with a letter, after that any letter or number (No spaces and most punctuation is out).Important note on saving Macros:Don’t save the macros in ‘All active templates and documents ‘(or All Open Workbooks). Choose only the active document or workbook!
205 What’s In a Program?Your program (a macro or a sub procedure in VBA) will be a list of instructions that will execute in a certain order and perform the task you tell it to.Let’s Start by learning a little about usingvariables and constants
206 What’s a VariableA named location in memory that’s used to store data.Variable names must begin with a letter, after that letters (upper case or lower case), numbers, and the underscore character can be used.It is a good idea to use meaningful variable names (i.e. UserName, OutsideRadius, Volume_1, and Pi)
207 Declaring VariablesIt is strongly recommended that you always declare yourvariables. This will help ensure your program runs correctlyA variable declaration statement looks like this:Dim VariableName as datatypeExamples:Dim Radius as Single, Area as SingleDim Count as IntegerDim StudentName as String
208 Declaring Variables Cont’d. There are many data types available, Single, Integer, and String are enough to get you started.Single is for real numbers (floating-point values) using single precisionInteger is for whole numbers (no decimal)String is for a sequence of text (anything can be text: letters, numbers, special characters, or spaces)Strongly Recommended: Use of the Option Explicit Statement which requires declaration of all variables
209 Mathematical operators (listed by order of precedence) ^Exponentiation-Negation* or /Multiplication or Division\Integer Division+ or -Addition or Subtraction
210 Assignment Statements VariableName = ExpressionThe = is not an equal sign like used in math, think of it more like and arrow pointing to the left(VariableName ← Expression).The statement evaluates the expression on the right side and assigns that value to the variable listed on the left side.X + 3 = Y (DOES NOT WORK! It has no meaning.)Y = X + 3 (YES! This is correct)
211 Assignment Statements Cont’d. An Expression can be constant (a number or a literal value)Count = 3UserName = “Martha Selby”An Expression can be another variable or a combination of valuesusing operatorsRadius = 2X = 5Pi = 4*Atn(1) (Atn is a function that calculates the arctangent)Volume = Pi*Radius^2X = RadiusAn Expression can also be a VBA function (we will cover some of these soon.)
212 A Beginning VBA Program (a temperature conversion program) Option ExplicitSub MyFirstProgram()'' MyFirstProgram Macro' Macro created 7/10/2003 by martha selby' To make comments, just use an apostrophe!‘Dim Celsius As Single, Fahrenheit As Single 'you can also add comments hereFahrenheit = 212Celsius = 5 / 9 * (Fahrenheit - 32)End SubNote: We really need to know how to do both input and output to write any meaningful programs!
213 Input/Output Lecture written by: Prof. Martha Selby Updated for presentation by: Emily VereenDate last updated: Summer 2003
214 Getting the Program to Communicate with the User Output (providing information to the user), using the Message Box functionMsgBox(prompt)(The prompt is all that is required, but there are many other optional arguments available)MsgBox(“This is a simple message box”)The prompt is a string argument, but you can use the concatenation, &, operator to join two strings or a string and a variable which holds a number (the number is really converted to a string, but we won’t worry too much about that).
215 Getting the Program to Communicate with the User cont’d MsgBox(“The answer is” & temperature)Assuming the variable, temperature, has a value of 212 stored in it, the message box would show:Notice we NEED to include a space in the String part of the prompt after the word is to get the message box to show.
216 The Temperature Conversion program revisited: Option ExplicitSub MyFirstProgram()'' MyFirstProgram Macro' Macro created 7/10/2003 by martha selby' To make comments, just use an apostrophe!‘Dim Celsius As Single, Fahrenheit As Single 'you can also add comments hereFahrenheit = 212Celsius = 5 / 9 * (Fahrenheit - 32)MsgBox ("For a fahrenheit temperature of " & Fahrenheit & " degrees.")MsgBox ("The celsius temperature = " & Celsius & " degrees.")End Sub
217 The Temperature Conversion program revisited: Here are the message boxes from the previous program:
218 Getting Input from the User Input (letting the user talk back to the program), using theInput Box functionVariableName = InputBox(prompt)(The prompt is all that is required, but there are many otheroptional arguments available)Radius = InputBox(“Enter the radius of the circle in meters.”)The InputBox function is limited to retrieving a single piece ofinformation from the user. The value that the user enters will beassigned to the variable on the left side of the = sign.
219 The Temperature Conversion Program revisted: Option ExplicitSub MyFirstProgram()' MyFirstProgram Macro' Macro created 7/10/2003 by martha selby‘Dim Celsius As Single, Fahrenheit As SingleFahrenheit = InputBox("Enter a temperature in Fahrenheit.")Celsius = 5 / 9 * (Fahrenheit - 32)MsgBox ("For a fahrenheit temperature of " & Fahrenheit & " degrees." & _"The celsius temperature = " & Celsius & " degrees.")End Sub*note the use of the line-continuation character in the MsgBox, the underscore _.
220 The InputBox and MsgBox from the previous program:
221 Multi-line Message Box or Input Box VBA will wrap longer string prompts in a MsgBox into two or more lines(however this does NOT happen in InputBoxes), but you can include the line-feed andcarriage-return characters in the prompt to cause the message to becontinued on another line when the boxes are displayed.vbCrLf is the VBA constant that represents the carriage return and line-feed constant.MsgBox ("For a fahrenheit temperature of " & Fahrenheit & " degrees." & vbCrLf _& "The celsius temperature = " & Celsius & " degrees.")
222 Input/Output Part II Lecture written by: Prof. Martha Selby Updated for presentation by: Emily VereenDate last updated: Summer 2003
223 Reading from and writing to a file. Before you can read from or write to a you must open the file using the Open statement.Open (“pathname”) For mode as filenumberExamples:Open (“U:\InputStuff.txt”) For Input as 1Open (“U:\OutputStuff.txt”) For Output as 2Mode can be Input, or Output (also Append and a few other choices we won’t go into).If mode is Input the file must exist before you run the program or you’ll get an error!Use a text editor like notepad to create your input file.
224 Reading from an open file. To read from a file you have created and Opened For Input using the Open statement, use the Input statement.Input #filenumber, varlistThe filenumber should match the filenumber used in the Open For Input statement.The varlist should be a comma-delimited list of variablesExamples:Open (“U:\InputStuff.txt”) For Input as 1Input #1, x, yCloseAlways remember to close a file with a Close statement:Close [filenumber] (if filenumber is omitted all open files are closed)
225 Example Program using Open and Input statements. The contents of AverageIn.txt before program runs:Option ExplicitSub Average()Dim Ave As Single, Exam1 As Single, Exam2 As SingleOpen (“U:\AverageIn.txt") For Input As 1Input #1, Exam1Input #1, Exam2Ave = (Exam1 + Exam2) / 2MsgBox ("The exam average = " & Ave)CloseEnd Sub9080You could have had one input statement:Input #1, Exam1, Exam2
226 Writing to an open fileA new file will be created by the computer if a specified file doesn’t exit whenopening in Output (or append) mode.To write to a file you have opened in Output mode you can use a Print or a Writestatement.Print statement: Print #filenumber, [outputlist]The filenumber should match the filenumber used in the Open For Output statement.The outputlist is a list of variables or expressions. It can be delimited withsemicolons, or commas. If there is no outputlist an empty line is written to the file.Examples:Open (“U:\OutputStuff.txt”) For Output as 2Print #2, “X = “; x; ” Y = “; yClose
227 Program with Input and Print statements Option ExplicitSub Average()Dim Ave As Single, Exam1 As Single, Exam2 As SingleOpen (“U:\AverageIn.txt") For Input As 1Open (“U:\AverageOut.txt") For Output As 2Input #1, Exam1Input #1, Exam2Ave = (Exam1 + Exam2) / 2Print #2, "The average of the exam scores = "; AveCloseEnd SubThe contents of the AverageOut.txt after the program runs:The average of the exam scores = 85
228 Writing to a file using a Write Statement Write and Print statements are very much alike.The main difference is in how they store the data they write tothe file.A Write # statement stores the data so that it can more easilyread back from the file using the Input # statement.The Write # statement automatically places quotation marksaround string data and delimits data fields with a comma.This makes it clear to the Input # statement where each dataitem begins and ends, and what type of data it is.
229 Example program with Write statement Option ExplicitSub Students()Dim Name As String, IDnumber As IntegerOpen (“U:\StudentsOut.txt") For Output As 3Name = InputBox("Enter a student's name.")IDnumber = InputBox("Enter last four digits of ID number.")Write #3, Name, IDnumberCloseEnd SubContents of StudentsOut.txt file after program runs:"Martha Selby",4432
230 Reading From a File Option Explicit Sub Students() Dim Name As String, IDnumber As IntegerOpen (“U:\StudentsOut.txt") For Input As 2Input #2, Name, IDnumberMsgBox(“Student’s name: “ & Name & vbCrLf & “Student’s ID: “ & IDnumber)CloseEnd Sub
231 Let’s try it with a file created by a Print statement Option ExplicitSub Students()Dim Name As String, IDnumber As IntegerOpen (“U:\StudentsOut.txt") For Output As 3Name = InputBox("Enter a student's name.")IDnumber = InputBox("Enter last four digits of ID number.")Print #3, Name, IDnumberCloseEnd SubContents of StudentsOut.txt file after program runs:Martha Selby
232 Read From a File Using a Print Statement Now let’s read from the file we just wrote to with a Print statement.Option ExplicitSub Students()Dim Name As String, IDnumber As IntegerOpen (“U:\StudentsOut.txt") For Input As 2Input #2, Name, IDnumberMsgBox(“Student’s name: “ & Name & vbCrLf & “Student’s ID: “ & IDnumber)CloseEnd SubWE GET AN ERROR!
233 Print # and Write # statements Print # statements are fine when you are creating a file thatyou just want to look at and/or print out (maybe Print isbetter for this since you don’t get the “ ” marks when youmay not want them).Write # statements are best for outputting heavilystructured data that then can be easily read and understoodby an Input # statement later.
234 Controlling the Flow Part 1: Decisions and Alternatives Lecture written by: Martha SelbyUpdated for presentation by: Emily VereenDate last updated: Summer 2003
235 Decisions and Alternatives A conditional statement allows a program to decide which piece of code to execute based on whether a condition is true or false, as shown in the flowchart:
236 How do you compare things in VBA? For a program to make a choice we have to learn how to write a true or false question (called a logical expression).VBA comparison operators:OperatorMeaning=Equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to<>Not equal to
237 Logical Condition (True or False questions) Comparison operators will be used to make logical expressionsthat have true or false answers:(Radius >= 5.0)(UserName = “Martha Selby”)((A^2 + B^2) = 10)
238 If Statement the one line If statement If Statement- A structure for makingdecisions and controlling the flow.We will look at a control structure called an Ifstatement (a structureusually involves more than oneprogramming statement and must bewritten following a certain template).We will look at four forms of the If statement.The most basic form of the If statement:the one line If statementIf (logical condition) Then statement
239 One Line If Statement cont’d When an If Statement needs to execute only a singlestatement if the condition is true you can put the wholestructure on one line (no End IF statement is required)If (X >= 0)Then Y=X ^ 0.5If the logical condition is True the statement following theThen will be executed; if it’s False the statement will beignored.
240 The next form of the If Statement: If Statement cont’dThe next form of the If Statement:The If … Then statementIf (logical Condition) Thenstatementstatement(s)End If
241 If … Then Statement cont’d The computer decides if the condition is true and if so itexecutes the statements between the IF and the End IF.If (ExamScore >=90) ThenMsgBox(“Congratulations, you got an A!”)LetterGrade = “A”End IfNote: The use of consistent indentation and parenthesis is vital to writing good, understandable code!
242 The next form of the If statement: If…Then…Else statementThis structure lets the programchose between two alternative branches of code to execute.If(logical condition) ThenStatement(s)…ElseEnd If
244 Getting More Complex More Than One Question to Ask: If…Then…ElseIf…Else statementYou can have as many ElseIf statementsas you want (to allow for as manybranches as you want).The Else statement is optionalIf (logical condition 1) Thenstatement(s) 1…ElseIf (logical condition 2) Thenstatement(s) 2Elsestatement(s) 3End If
245 If-Then-Else if, Example Flowchart Isb2 - 4ac < 0?YESNOIsb2 - 4ac > 0?NOYESx1 = -b + b2 - 4ac2a“No RealSolution”x = -b/2ax2 = -b b2 - 4ac2aOutputxOutputx1 and x2See code on next slide
246 Example If-Then-Else if Structure If( b ^ * a * c < 0) ThenMsgBox(“No real solution”)ElseIf (b ^ * a * c > 0)Thenx1 = (- b + Sqr(b ^ * a * c)) / (2 * a)x2 = (- b - Sqr(b ^ * a * c) )/ (2 * a)MsgBox(“The real roots= “ & x1 & “ and “ & x2)Elsex = -b / (2 * a)MsgBox(“The real root = “ & x)End IfSee previous slide for flowchart
247 More on logical Conditions You can get more complicated with your logical conditions also.You can test multiple conditions to decide a final true or false.VBA has logical operators:ANDConjunction (only if both sub expressions are true it is True)ORDisjunction (if either or both sub expressions is true it is True)NOTNegation
248 Controlling the Flow Part 2: Loops Lecture written by: Martha SelbyUpdated for presentation by: Emily VereenDate last updated: Summer 2003
249 What is a Loop?A loop is a structure that is used to REPEAT a series of statements. A loop has a beginning and an end. When the program gets to the end of the loop structure, it “loops” back to the beginning and starts the statements over.There are two types of loops:A loop that repeats an indefinite number of times (in VBA, a DO …EXIT DO … LOOP)A loop that repeats a fixed number of times (in VBA, a FOR … NEXT loop)
250 Using a Do… Exit Do… Loop Structure:Dostatement(s)conditional exit using Exit Do statement (this can be anywhere inside the loop, but it should only be used once)LoopVBA has many Do Loop structures: Do While .. Loop, Do .. Loop While, Do Until … Loop and Do … Loop Until,However the Do …Exit Do .. Loop structure is all you need!
251 Example Program with a Do Loop Option ExplicitSub MyFirstProgram()' MyFirstProgram Macro' Macro created 7/10/2003 by martha selbyDim Celsius As Single, Fahrenheit As SingleDim Answer As StringDoFahrenheit = InputBox("Enter a temperature in Fahrenheit.")Celsius = 5 / 9 * (Fahrenheit - 32)MsgBox ("For a fahrenheit temperature of " & Fahrenheit & " degrees.")MsgBox ("The celsius temperature = " & Celsius & " degrees.")Answer = InputBox("So you want to repeat this? (Y or N)")If ( (Answer = "N“ ) Or ( Answer = "n") ) Then Exit DoLoopEnd Sub
252 Another program with a Do…Exit Do… Loop Option ExplicitSub SumIntegers()' SumIntegers Macro' Macro created 7/18/2003 by mselbyDim Sum As Integer, n As IntegerSum = 0n = 1DoIf (n ^ 2 > 1000) Then Exit DoSum = Sum + nn = n + 1LoopMsgBox ("The final sum = " & Sum)End Sub
253 For…Next Loop When you know how many times you want to loop then use a For … Next loop.Structure:For counter = start To end [Step stepsize]statement(s)Next counterExample:For i = 1 To ‘ stepsize is 1 by defaultSum = Sum + iNext i
254 For…Next Loop Here’s what happens in a For .. Next loop: When VBA enters the loop at the For statement, it assigns the start value to counter (which is a variable that must in the Dim statement). It then goes through the loop, when it reaches the Next statement, it increments counter by stepsize (or 1) and loops back to the For statement.VBA checks the counter variable against the end value, if counter is greater than end VBA exits the loop, otherwise it continues through the loop. (If stepsize is negative VBA will exit the loop when counter is < the end value)To exit a For loop early you can use a Exit For statement.
255 What does this program do? For…Next Loop ExampleOption ExplicitSub Example()‘' Macro created 9/30/2002 by Martha Selby'Dim N as Integer, sum as Integer, J As Integersum = 0N = InputBox("Enter an positive integer number >= 3")For J = 1 To N Step 2sum = sum + JNext JMsgBox ("The final sum =" & sum)End SubWhat does this program do?
257 Nesting LoopsYou can nest one or more loops within another loop, you can even nest For and Do loop together.Indentation is VERY important when nesting loops!For j = 1 To 3For n = 1 to 2MsgBox(“j = “ & j & “ and n = “ & n)Next nNext jResults:j = 1 and n = 1 Note: The inside loop is executedj = 1 and n = times for each of the 3 timesj = 2 and n = 1 the outside loop executes.j = 2 and n = 2j = 3 and n = 1j = 3 and n = 2
258 One-Dimensional Array Lecture written by: Martha SelbyUpdated for presentation by: Emily VereenDate last updated: Summer 2003
259 What’s an Array?An array is a special type of variable that can hold many values at once.An array is a way to group a set of data and store it under one name.A simple array (a one-dimensional array) should be pictured like a list.Each individual item in the list is an element of the array.
260 One Dimensional Array Example (a list of numbers) A list of surefire lottery numbers, stored in an array named, LottoLotto(1) =Lotto(2) =Lotto(3) =Lotto(4) =Lotto(5) =Lotto(6) =An individual element in the array is referred to with the array name and an index (a positive number) which specifies the position in the array for that element.ArrayName(indexNumber)A one dimensional array is just like a subscripted variable you’ve used in math, X1 , X2 , X3 , … Xi
261 Creating or declaring an array To declare an array use the Dim statement to tell the computer the type of variable the array is and it’s size.Dim MyArray(5) as SingleDim Lotto(1 to 10) as IntegerThese are Fixed Size arrays (there are dynamic arrays also).You can created any type of array, but arrays can only hold one data type(using variant type gets around this limitation but is not recommended).Note: All VBA arrays start with the index 0 by default, so MyArray has elementsthat range from MyArray(0) to MyArray(5).
262 Storing Values in an Array To assign a value to an item in an array, just use the index number to identify the item.Dim Lotto(1 to 10) as IntegerLotto(1) = InputBox(“Enter lotto first number”)Lotto(2) = InputBox(“Enter lotto second number”)This is certainly not a very efficient means of accessing the array elements. A good wayto do anything with multiple arrays elements is to use a For … Next loop!For j = 1 to 6Lotto(j) = InputBox(“Enter a lotto number”)Next jNote: The For .. Next loop variable is used for the array index, so the loop changes the value of the index each time through.
263 Example ProgramThe Program, finds the mean of array values and prints only the ones greater than mean.Option ExplicitSub Failure()Dim FailureTimes(1 To 10) As Single, MeanFailure As Single, Sum As SingleDim J As IntegerOpen (“U:\failure.dat") For Input As 1Open (“U:\failure.out") For Output As 2Sum = 0For J = 1 To 10Input #1, FailureTimes(J)Sum = Sum + FailureTimes(J)Next JMeanFailure = Sum / 10Print #2, "The mean time to failure ="; MeanFailurePrint #2,Print #2, " List of raliure times greater than the mean:"If (FailureTimes(J) > MeanFailure) Then Print #2, FailureTimes(J)CloseEnd Sub
264 There are many built-in array functions Lbound and Ubound are the names of array functions that letyou find out the size of an array.ReDim is used to size an array that has been declared adynamic array.The list goes on and on… You can discover others as you find a need for certain functions.
265 Multi-Dimensional Arrays Lecture written by: Prof. Martha SelbyUpdated for presentation by: Emily VereenDate last updated: Summer 2003
266 Multi-Dimensional Arrays Arrays can have multiple dimensions (meaning multiplesubscripts).Multidimensional arrays in VBA can contain up to 60dimensions! But don’t worry it’s extremely rare to use morethan 2 or 3 dimensions.In Engr 160 we’re going to stick to two dimensions!
267 Two-Dimensional arrays 2-D array have two subscripts.Dimension them by separating the dimensions with a comma.Examples:Dim MyArray(1 to 20, 1 to 50) as Single, Calendar(1 to 12, 1 to 31) as StringDim X(5,6) as IntegerA 2_D array can be thought of like a table or a spreadsheet, having rows and columns.In the array Calendar dimensioned above, each of the 12 rows could be a month and eachof the 31 columns could be a day in a month. You could assign a value to each position ofthe Calendar array and it would be associated with a month and a day.Calendar(1,1) = “Wednesday” ‘January,1st is a Wednesday.Calendar(1,2) = “Thursday” ‘January, 2nd is a Thursday.
268 Two-Dimensional arrays cont. Since 2_D arrays have 2 subscripts they often take 2 nested For-Next Loops tomanipulate them.Entering data into a 2-D array:For J = 1 to 12For K = 1 to 31Calendar(J,K) = InputBox(“Enter the correct day”)Next KNext JHow can you tell in what order the Calendar array is filling the elements? Is itfilling a month at a time? How could you change this?
269 2-D Array Example Problem Find theaverage foreach row andthe overallthe entirematrixX(1,1)X(1,2)X(1,3)X(1,4)X(2,1)X(2,2)X(2,3)X(2,4)X(3,1)X(3,2)X(3,3)X(3,4)X(4,1)X(4,2)X(4,3)X(4,4)X(5,1)X(5,2)X(5,3)X(5,4)X(6,1)X(6,2)X(6,3)X(6,4)
270 Example Program with 2-D arrays Option ExplicitSub Ave2D()Dim X(1 To 6, 1 To 4) As SingleDim RowAve(1 To 6) As Single, Sum As SingleDim Total As Single, TotAve As SingleDim J As Integer, K As IntegerOpen (“U:\AveIn.txt") For Input As 1Open (“U:\AveOut.txt") For Output As 2Total = 0For K = 1 To 6For J = 1 To 4Input #1, X(K, J)Next JNext KSum = 0Sum = Sum + X(K, J)Total = Total + X(K, J)RowAve(K) = Sum / 4TotAve = Total / 24Print #2, "Overall average = " ; TotAvePrint #2,For K = 1 To 6Print #2, "The row #" ; K ; " average = " ; RowAve(K)Next KCloseEnd Sub
271 Functions – Using and Creating Lecture written by: Prof. Martha SelbyAuthored for presentation by: Emily VereenDate last updated: Summer 2003
272 What is a Function?A function is a type of procedure or program (a sub is another type of procedure).Functions take arguments (except in rare cases) and return avalue by having the name of the function actually assigned a value.That means you send functions information and it doessomething and spits back a value.In VBA functions are essential and there are a huge varietyof built-in functions already available.
273 Built-in FunctionsFunctions are available to do such things as manipulate string variables,format numbers, dates or times, and convert data from one format toanother (also there’s the usual numeric functions)To use a function you need to know it’s name and it’s requiredarguments.You call or invoke a function from a sub procedure (or anotherfunction) by using it’s name with the argument list.Name [ , argumentlist]The argumentlist is a comma-delimited list of variables, arrays, orexpressions to pass to the function.Note: The Name of the function will have the return value assigned to it.
274 Built-in Function examples 1) Atn(numbervariable)returns the arctangent of numbervariable in radians2) Exp(numbervariable)returns e raised to the power of numbervariable3) FormatNumber(number[,DecimalPlaces],returns number formatted to 2 decimal places as default or as many asyou specify)
275 Example program using built-in functions Option ExplicitSub ExampleFunctions()' ExampleFunctions Macro' Macro created 7/22/2003 by mselbyDim Pi As Single, NLog As SinglePi = 4 * Atn(1)NLog = Exp(1)MsgBox ("This is the way to calculate pi = " & Pi)MsgBox ("This is the base of the natural log = " & NLog)MsgBox ("This will show 3 digits beyond the decimal. “ & FormatNumber(NLog, 3))End SubExit
276 Program Results:First MsgBoxSecond MsgBoxThird MsgBox
277 Creating Your own Functions A function is a type of program that can be used byanother program. When called by another program afunction will calculate and return a value (by having the Name takeon a value)To create a function you use a Function Statement:Function NameYouPick(argumentlist [as type]) as typestatement(s)NameYouPick = expressionEnd Function
278 Example FunctionFunction DeFunc(ByVal x as Integer, ByVal y as Integer) as IntegerDim z as Integerz = x + yDeFunc = x ^ zEnd Function
279 Important Notes on Functions Arguments are values that VBA is to transfer, or pass, from oneprocedure to another. Within the Function that receives thearguments they act just like any other variables. You really should declarethe type of each argument in the list (as Single or as Integer, etc.).Notice the as type declaration after the (argumentlist). This is declaringthe Function Name’s type.You must have a statement in the Function that assigns a value to theFunctionName. In the example it was:DeFunc = x ^ zTo access or call a Function from another procedure, you simply usethe Name of the Function with its argumentlist.ZSub = Defunc(3, 4) (this belongs in the calling program)
280 Example Function and Calling Sub Procedure Option ExplicitSub TestForSmog()Dim CarYear As Integer, ThisCar As StringCarYear = InputBox("Enter the year of your car.")ThisCar = NeedsSmog(CarYear)If (ThisCar = "Yes") ThenMsgBox ("Your car needs a smog check.")ElseMsgBox ("Your car does not need a smog check.")End IfEnd SubFunction NeedsSmog(ByVal CarYear As Integer) As StringIf (CarYear <= Year(Now) - 3) ThenNeedsSmog = "Yes"NeedsSmog = "No"End Function
281 Passing ArgumentsYou can pass arguments into a procedure two different ways.The default method is by reference (ByRef). When an argument ispassed by reference the recipient procedure gets access to thememory location where the original variable is stored and canchange the original variable.The other method is by value (ByVal). When an argument ispassed by value the recipient procedure gets only a copy of theinformation in the variable and can’t change the original.
282 Example of passing by default (ByRef) Option ExplicitSub DeSub()' DeSub Macro' Macro created 7/28/2003 by mselbyDim ZSub As Integer, XSub As Integer, YSub As IntegerXSub = 3YSub = 4ZSub = DeFunc(XSub, YSub)MsgBox ("ZSub =" & ZSub & vbCrLf & "XSub = " & XSub & _vbCrLf & "YSub =" & YSub)End SubFunction DeFunc(ByRef x As Integer, ByRef y As Integer) As IntegerDim z As Integerz = x + yDeFunc = x ^ zx = 15y = 20End Function
283 Example of passing by value (ByVal) Option ExplicitSub DeSub()' DeSub Macro' Macro created 7/28/2003 by mselbyDim ZSub As Integer, XSub As Integer, YSub As IntegerXSub = 3YSub = 4ZSub = DeFunc(XSub, YSub)MsgBox ("ZSub =" & ZSub & vbCrLf & "XSub = " & XSub & _vbCrLf & "YSub =" & YSub)End SubFunction DeFunc(ByVal x As Integer, ByVal y As Integer) As IntegerDim z As Integerz = x + yDeFunc = x ^ zx = 15y = 20End Function
284 Subprogram as Subs or Subroutines Lecture written by: Prof. Martha SelbyUpdated for presentation by: Emily VereenDate last updated: Summer 2003
285 Subprograms Subprograms can be Functions or Subs (subroutines) There are several advantages to splitting your largeprogram up into many smaller subprograms.Dividing your program into several smaller named procedures makes the code easier to write and understand.You can repeatedly access a subprogram from anotherProcedure or reuse many times in one procedure.Dividing the program into many subprograms would make it easy to divide the work among many programmers.
286 Calling a Sub You can access or call any Sub (or subroutine) from another Sub procedure.To do so you should use a Call Statement:[Call] procedurename (,argumentlist)One of the main differences between accessing aFunction and a Sub is that a Sub does not have a valueassociated with it’s name, and it is accessed using a Call statement
287 Example of a Sub (or subroutine) as a subprogram. Option ExplicitSub Main()' Main MacroDim R As Single, Theta As Single, X As Single, Y As SingleR = InputBox("Enter the distance r of the polar coordinates.")Theta = InputBox("Enter the angle in radians.")Call Convert(R, Theta, X, Y)MsgBox ("Given the polar coordinates as: " & R & ", " & Theta & _vbCrLf & "The rectangular coordinates are: " & X & ", " & Y)End SubSub Convert(ByVal R As Single, ByVal Theta As Single, ByRef X As Single, ByRef Y As Single)X = R * Cos(Theta)Y = R * Sin(Theta)
288 Returning values from a Sub In a Sub procedure that is accessed fromanother procedure, the way values can bereturned is through the argument list (No value isever associated with the Sub’s name).You can think of some of the variables in anargument list as passing values in to the sub and someas passing values out of the Sub.How does this affect the use of ByVal and ByRef in theargument list?
289 Example Revised using ByVal for passing arguments: Note the answers are WRONG!Option ExplicitSub Main()' Main Macro' Macro created 7/30/03 by mselbyDim R As Single, Theta As Single, X As Single, Y As SingleR = InputBox("Enter the distance r of the polar coordinates.")Theta = InputBox("Enter the angle in radians.")Call Convert(R, Theta, X, Y)MsgBox ("Given the polar coordinates as: " & R & ", " & Theta & _vbCrLf & "The rectangular coordinates are: " & X & ", " & Y)End SubSub Convert(ByVal R As Single, ByVal Theta As Single, ByVal X As Single, ByVal Y As Single)X = R * Cos(Theta)Y = R * Sin(Theta)
290 Example Revised with mixed ByVal and ByRef for passing arguments Option ExplicitSub Main()' Main Macro' Macro created 7/30/03 by mselbyDim R As Single, Theta As Single, X As Single, Y As SingleR = InputBox("Enter the distance r of the polar coordinates.")Theta = InputBox("Enter the angle in radians.")Call Convert(R, Theta, X, Y)MsgBox ("Given the polar coordinates as: " & R & ", " & Theta & _vbCrLf & "The rectangular coordinates are: " & X & ", " & Y)End SubSub Convert(ByVal R As Single, ByVal Theta As Single, ByRef X As Single, ByRef Y As Single)X = R * Cos(Theta)Y = R * Sin(Theta)Note the answers are Correct!This is the same as the first example.
291 Final words on ByVal vs. ByRef Remember:Arguments bringing in values that youdon’t want changed in the subprogramshould be passed ByVal; since ByValpasses only a copy of the value and theoriginal value in the main program willnot be changed.
292 Subprograms with Arrays Lecture written by: Prof. Martha SelbyAuthored for presentation by: Emily VereenDate last updated: Summer 2003
293 Subprograms (a Functions or a Subs) with Arrays as arguments To pass a whole array to a subprogram use the arrayname in the argument list followed by emptyparentheses.Call MySub(MyArray(), Radius, Volume)Also Arrays must be passed ByRef only!
294 Example using a Sub with arrays Option ExplicitSub Ave2D()Dim X(1 To 6, 1 To 4) As Single, Total As SingleDim TotAve As SingleDim J As Integer, K As IntegerOpen (“U:\AveIn.txt") For Input As 1Open (“U:\AveOut.txt") For Output As 2Total = 0For K = 1 To 6For J = 1 To 4Input #1, X(K, J)Next JNext KCall CalAve(X(), Total)TotAve = Total / 24Print #2, "Overall average = " & TotAveCloseEnd SubSub CalAve(ByRef X() As Single, ByRef Total As Single)Dim K As Integer, J As IntegerFor K = 1 To 6For J = 1 To 4Total = Total + X(K, J)Next JNext KEnd Sub
295 Example program, finds largest in a table of values. Option ExplicitSub Large()Dim Table(1 to 4, 1 to 3) As Single, Big As SingleDim L As Integer, M As IntegerOpen (“U:\largest.dat") For Input As 1Open (“U:\Largest.out") For Output As 2For L = 1 To 4For M = 1To 3Input #1, Table(L, M)Next MNext LFor M = 1 To 3Print #2, Table(L, M),‘note , end of line prints all values from inner loop on 1 linePrint #2, vbCr‘note this is a carriage return, to go to a new print lineBig = Largest(Table())Print #2,Print #2, "The largest value = " & BigCloseEnd SubFunction Largest(ByRef Table() As Single) As SingleDim H As Integer, J As IntegerLargest = Table(0, 0)For H = 1 To 4For J = 1 To 3If (Table(H, J) > Largest) Then Largest = Table(H, J)Next JNext HEnd FunctionLargest.out file contents:The largest value = 55
296 Excel VBA Programming Lecture written by: Prof. Martha Selby Authored for presentation by: Emily VereenDate last updated: Summer 2003
297 VBA and ObjectsVBA is a programming language that can interact with objects.Objects have properties and methods and events that can be changed or invoked.A simple analogy is a bicycle (an object).A bicycle has a color and size (these would be properties of the object).A bicycle can perform actions, like moving (this is a method)A bicycle could get a flat tire (this is an event; events are triggered by anexternal stimulus).The notation used is a dot notation with a left to right hierarchy.ActiveSheet.Range(“A1”).Font.Bold = TrueThe above is of the form of object.object.object.property = valueWhat do you think that statement does?
298 Working with cells and ranges in an Excel worksheet Excel uses what’s called A1 notation for celladdresses, (column letter and row number).But you’ll also see R1C1 notation (row numberand column number), which can be confusing!Cell B3 would be R3C2.
299 The Range ObjectThe Range object represents a group of one or more contiguous cells in a worksheet.Examples: Range(“A1”) Range(“A1:G1”)The Range object has a Value property that you can use in your programs to get the valuefrom a cell or to assign a value to a cell.To get a value from a cell and assign it to a variable:VariableName = Range(“A1”).ValueTo put a value stored in a variable or the result of an expression into a cell:Range(“A1”).Value = VariableName or expressionExamples:Range(“A1:B10”).Value = 2StudentName = Range(“E3”).Value
300 The Cells ObjectAnother way to reference a range is to use to use Cells (nothere is no such thing as Cell)Cells(rowIndex, columnIndex) , this is like the R1C1notationCells(3,2).Value = 5 ‘this assigns the number 5 to Cell B3
301 Active CellThe active cell is the cell(s) that is highlighted or selected in an Excel sheet.To control, move or find the active cell you can use the ActiveCell propertyYou could use Active Cell to get a value from a cell:VariableName = ActiveCell.Value ‘ you need to know where the active cell is!Or put a value into a cell:ActiveCell.Value = VariableName or expressionTo move the active cell – use the Select method.Range(“C3”).Select ‘now cell C3 is the active cellCells(5,12).Select ‘now cell L5 is the active cell
302 Active Cell cont.Another way to move the active cell is in a relative sense, using the Offset property.ActiveCell.Offset(rowOffset, columnOffset).SelectPositive rowOffset is down and positive columnOffset is to the right.(Negative is up and left).ActiveCell.Offset(1,2).Select‘this moves the active cell down one row and over two columns from where it was.ActiveCell.Offset(3,0).Select‘this moves the active cell down 3 row and in the same column.ActiveCellOffset(-2,0).Select‘this moves the active cell up 2 rows and in the same column.
303 Example Excel Program Option Explicit Sub CellDataDemo() Dim radius As Single, i As IntegerRange("B2").Select 'Moving active cell to B2For i = 1 To 3radius = ActiveCell.ValueActiveCell.Offset(0, 1).SelectActiveCell.Value = 4 / 3 * (4 * Atn(1)) * radius ^ 3ActiveCell.Value = 4 * (4 * Atn(1)) * radius ^ 2ActiveCell.Offset(1, -2).SelectNext iEnd Sub
304 Excel WorkSheet from last program. Before program execution:Excel VBA Demo:Radius, mVolume, m^3Surface Area, m^25.006.007.00After program execution:Excel VBA Demo:Radius, mVolume, m^3Surface Area, m^25.00523.60314.166.00904.78452.397.00615.75