Download presentation

Presentation is loading. Please wait.

Published byRicardo Claycomb Modified about 1 year ago

1
ENGINEERING 160 Algorithms and Flowcharts Intro to Programming Input/Output Part One Part Two Controlling the Flow Part 1: Decisions and alternatives Part 2: Loops One Dimensional Arrays Multi-Dimensional Arrays Functions Subprograms as Subs or Subroutines Subprograms with Arrays VBA Lessons: Engineering 160 Engineering Problem Solving Lessons: Excel VBA Programming Problem Presentation in Engineering Dimensions and Units Estimation Analysis in Design Graphing and Curve Fitting Part One Part Two Statistics Spreadsheets and MS Excel Part One Part Two Engineering Economy Statics Class Introduction Copyright, Iowa State University

2
Engineering 160 Introduction to Engineering 160 Originally authored by: Mark Sobek Authored for presentation by: Julie Sandberg Date last updated: 8/9/01

3
Engineering 160 (2) 1 hr. 50 min. lectures with labs on PC’s

4
Engineering 160 Open Labs: 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
Engineering 160 Class Policies: Class Policies: u Classroom procedures u Programming proficiency score required (60% on exams) u Grading u Instructor’s office hours

6
Engineering 160 ENGR Course Objectives u To expose students to a wide variety of engineering problems similar to material they will study in greater depth later. u To help students learn to translate verbal, written or graphical problems into mathematical models. u 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 u To help students develop an orderly process of presenting the calculations required in solving engineering problems so that others may readily understand their work. u To prepare students to communicate results of their work through graphs, charts, etc. u To prepare students for the process of solving engineering problems via a computer programming and use of a spreadsheet. Engineering 160

8
Problem Presentation in Engineering Initially authored by: Mark Sobek Authored for presentation by: Julie Sandberg Date last updated: 8/ 8/ 01

9
Engineering 160 Steps in Problem Solving u Recognize and understand the problem. u Accumulate all the facts available: Determine all known and unknown variables. u Make necessary assumptions u Select an appropriate theory to solve the problem. u Solve the problem. u Verify and check the solution.

10
Engineering 160 Guidelines for Problem Presentation 1. Use engineering problems paper (plain side). 2. Top heading of paper should be completed as follows: 3. Work should be in pencil. (except for computer output) Due Date Course No. Problem Nos. Name Pg Tot (Word processing may be required. Some rules apply only to handwritten work)

11
Engineering 160 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
Engineering 160 Physical Problem Layout: Due Date Course No. Problem Nos. Name 1 2 Problem Statement: State the problem to be solved. Include the problem number. Diagram: A diagram with all pertinent data (known and unknown) should be shown. “One picture is worth a thousand words.” Assumptions: List all assumptions used in the solution process.

13
Engineering 160 Physical Problem Layout 2: Due Date Course No. Problem Nos. Name 2 2 Theory: Present the theory used. If an equation must be derived, do it in the theory section. Reference all equations. Define all variables. Solution: Show all important steps in obtaining the solution. Discussion/Conclusion: Discuss the results obtained. Present your conclusions.

14
Engineering 160 Physical Problem Layout 3: 1/21/01 Engineering 160 Example 1 Sobek, Mark 1 2 Problem Statement: Determine the volume and mass of water contained in the cylindrical water tank shown below. Diagram: Assume: 1. Tank is full. 2. Inside dimensions are given 3. Water is at 50°F 40.0 ft 20.0 ft Water density at 50°F is 1 kg/L

15
Engineering 160 Physical Problem Layout 4: 1/21/01 Engineering 160 Example 1 Sobek, Mark 2 2 Theory:V = ( /4)D 2 H m = V Where: V = Tank volume L D = Tank diameter m H = Tank height m m = Water mass kg = Water density kg/L Solution: V = ( /4)(40 ft) 2 (20 ft) = (10 5 ) ft 3 = (10 5 ) ( L/ft 3 ) = 7.12 (10 5 ) L m = (1 kg/L)(7.12 (10 5 ) L) = 7.12 (10 5 ) kg

16
Engineering 160 Physical Problem Layout 5: 1/21/01 Engineering 160 Example 2 Sobek, Mark 1 3 Problem Statement: Determine the length of side UT of the land plot shown below. Evaluate the area. Diagram: 120 m 130 m 90 m Obstruction T U R S 115° 100° Assume: 1. The plot of land is planar

17
Engineering 160 Physical Problem Layout 6: 1/21/01 Engineering 160 Example 2 Sobek, Mark 2 3 Theory: Apply the Law of Cosines to RST: RT = [RS 2 + ST 2 - 2(RS)(ST)cos( RST)] 1/2 Apply the Law of Sines: = sin -1 [(RU/RT)sin( RUT)] = 180º- RUT - Apply the Law of Sines: UT = (RT) sin( )/sin( RUT) Area RSTU = Area RST + Area RTU = (1/2)(RS)(ST)sin( RST) +(1/2)(RU)(UT)sin( RUT )

18
Physical Problem Layout 7: 1/21/01 Engineering 160 Example 2 Sobek, Mark 3 3 Solution: RT = [(120) 2 + (90) 2 - 2(120)(90)cos(115º)] 1/2 = m = sin -1 [(130/177.8)sin(100°) = 46º = 180º - 100º - 46º = 34º UT = (177.8)sin(34º)/sin(100º) = 101 m Area RSTU = (1/2)(120)(90)sin(115º) +(1/2)(130)(101)sin(100º) = m 2 Engineering 160

19
Dimensions and Units Lecture written by: Dr. James Hilliard Authored for presentation by: Julie Sandberg Date last updated: 6/16/98

20
Engineering 160 Example: Consider the following mechanical system: Mass Velocity Motion Path Y X Z System Description - In order to describe the above system, one needs to define a set of physical parameters. Mass Velocity Etc. Time Momentum Length Energy

21
Engineering 160 Definitions: Dimensions - The set of physical parameters used to define the state of a system. Units - A standard quantity that allows one to establish a value for a dimension. A = (N) (U) Physical Quantity Numerical Value Unit

22
Engineering 160 Fundamental and Derived Dimensions Fundamental Dimension - A dimension that cannot be derived from other dimensions. Derived Dimension - A dimension that can be defined by some mathematical combination of fundamental dimensions.

23
Engineering 160 Example: Let length (L) and time (T) be fundamental dimensions. Let velocity (V) be another dimension used to describe a system state. A relationship exists as follows: V = L / T Therefore, velocity is a derived dimension!

24
Engineering 160 Dimensional System Dimensional System - The smallest set of fundamental dimensions that can be used for a complete study of a field of science. Examples: (Systems used in Mechanics) “Absolute System” -Fundamental dimensions are length, mass, time. “Gravitational System” -Fundamental dimensions are length, force, time.

25
Engineering 160 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/s 2 ) In U.S. units: F = Force (lb) M = Mass (slug) 2 ) A = Acceleration of gravity (ft/s 2 )

26
Engineering 160 The SI Metric System: During the past several years, many types of unit systems have been in use. Generally, they were variations of two types: (1) British System (2) MKS Metric The new common system being adopted is the SI Metric System!

27
Engineering 160 Unit Classes The SI metric system contains 3 classes of units: (1) Base units (2) Supplementary Units (3) Derived Units

28
Engineering 160 Base Units: QuantityNameSymbol Length Mass Time Electric Current Thermodynamic Temperature Amount of a Substance Luminous Intensity Meter Kilogram Second Ampere Kelvin Mole Candela m kg s A K mol cd

29
Engineering 160 Supplementary Units: QuantityNameSymbol Plane angle Solid angle Radian Steradian rad sr

30
Engineering 160 Example: The density of water at 50ºF is about 1.94 slug/ft 3. Determine the volume 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. Express volume in cubic meters and mass in kilograms. Vol = R 2 H = (25.0 ft) ft ( m) 3 ft 3 = 1946 = 1.95 x 10 3 m 3 Mass = (Vol)(Density) = (25.0 ft) ft 1.94 slug kg ft 3 slug = 1.95 x 10 6 kg 50.0 ft 35.0 ft

31
Engineering 160 Numbers & Errors Types Of Errors: * Systematic (Bias) * Accidental (Statistical) Note: Precision, which is a measure of error, is properly conveyed numerically by using appropriate significant digits.

32
Engineering 160 Significant Figures Significant figures are figures (digits) used in writing a number, except those used to define only the decimal location such as: 2000, 200, , ETC. Or those zeros which do not have non-zero digits on their left , , ETC.

33
Engineering 160 Rules for Handling Significant Figures u Rounding Numbers u Multiplication Rules (Division Rules) u Addition Rules (Subtraction Rules)

34
Engineering 160 Rounding Numbers u If the first digit discarded is < 5, leave the last digit kept unchanged. u If the first digit discarded is > = 5, increase the last digit kept by 1.

35
Engineering 160 Rules for Addition (Subtraction) Rules for Addition (Subtraction) u The answer should show significant digits only as far to the right as is seen in the least precise number. u Find the least precise number. u Add (Subtract) the numbers. u Round the answer such that the last significant digit is no farther right than that of the least precise number.

36
Engineering 160 Example (Rules for Addition or Subtraction)

37
Engineering 160 Rules for Multiplication (Division) The product or quotient shall contain no more significant digits than are contained in the number with the fewest significant digits initially. Example: (27.08)/(19) = = 1.4

38
Example (Proper Use of Significant Figures) Engineering 160 Convert miles to kilometers: miles km mile = km Thus, the final answer (16.09 km) contains 4 significant figures just like the miles did.

39
Engineering 160 Estimation Lecture written by: Dr. James Hilliard Authored for presentation by: Julie Sandberg Date last updated: 6/ 18/ 98

40
Engineering 160 Estimation Engineers continually make estimations. Calculated results are always suspect until the reasonableness of the answer is verified by estimation. Much embarrassment can be avoided by checking calculated results with a quick estimate.

41
Engineering 160 Basis of Estimation The estimate is directly influenced by: A. Time available B. Physical circumstances such as: 1. Reference material at hand 2. Access to a phone 3. Computational equipment available

42
Engineering 160 Estimates and Engineers The soundness of an engineer’s judgement will be tested in many planning sessions. Estimates often decide which plans to explore in more depth and detail. Experience, logic, and communication skills will determine if your voice is heard.

43
Engineering 160 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 can easily explain and defend it. D. Further refinement of your estimate should be straightforward and easy to implement.

44
Engineering 160 Estimation Format Example Problem Statement: Estimate the volume of your pencil in cubic mm Assumptions (A) Cylindrical shape Estimates (A) 5 inches in length (B) 0.25 inches in diameter Engineering 160 Example 1 2 Sobek, Mark

45
Example cont. Theory: Vol = (Length)( )(Radius) 2 Calculations: Length = (5 in)(25.4 mm/in) = 127 mm Radius = (0.25/2 in)(25.4 mm/in) = mm Vol = (127 mm)( )(3.175) 2 = 4022 mm 3 ~ 4000 mm 3 Engineering 160 Example 2 2 Sobek, Mark Engineering 160

46
Analysis in Design Lecture written by: Dr. James Hilliard Authored for presentation by: Julie Sandberg Date last updated: 6/ 18/ 98

47
Engineering 160 Analysis in Design A design must be analyzed in detail to be certain that expectations are met. The analysis involves calculating the response of the design at many operating points. At every operating point, the same calculations are made and hence the term was developed:

48
Engineering 160 Repeated Analysis Repeated analysis is an excellent application for computers. Computer routines can loop many times per second and with each loop, the solution at yet another operating point is obtained.

49
Engineering 160 Repeated Analysis etc. Since the computer can do the hard labor so quickly, many variations of the design can be tried - leading to optimization. Computer output must normally be graphical in order to allow a quick grasp of the “blizzard” of numerical results.

50
Engineering 160 Example Problem Cable Pin H

51
Engineering 160 Example cont. Free Body Diagram H AxAx AyAy T ßMg L Governing Equations: 1. ß = ARCTAN[(L sin - 2H)/L cos ] 2. A x = T cos ß 3. A y = T sin ß + Mg 4. A = (A x 2 + A y 2 ) 1/2 5. T = (2 Mg cos )/(cos ß sin - sin ß cos )

52
Engineering 160 Table of Values (Degrees) T (Newtons)A (Newtons)

53
Crane Data Graph BOOM ANGLE (degrees) P I N & C A B L E L O A D (N) T A Engineering 160

54
Graphing and Curve Fitting Part One Lecture written by: Prof. Martha Selby Authored for presentation by: Julie Sandberg Date last updated: 8/ 06/ 07

55
Engineering 160 Representation of Technical Data u Collecting data u Recording and presenting data u Tabular form u Graphical form u Data analysis u Identification of equation showing functional relationships Experimental Process Steps:

56
Engineering 160 Steps in the Proper Construction of a Graph 1. Select proper type of graph paper A. Uniform grid - Rectilinear: i.e., 20 lines/inch 10 lines/cm B. Non-uniform grid - Log-log (#of cycles/axis?) Semi-log

57
Engineering 160 Steps in the Proper Construction of a Graph 2. Choose proper location of axes A. Place axes inside the edge of the printed grid B. Plot should use as much of the grid as possible, consistent with good scale rules. Abscissa, x axis Independent variable Ordinate, y axis Dependent variable

58
Engineering 160 Steps in the Proper Construction of a Graph 3. Calibrate the axes: Assign numerical values to the graduations Graduation Calibration

59
Engineering 160 Steps in the Proper Construction of a Graph Follow the 1, 2 5 rule On a uniform scale the value of the smallest division must be 1, 2, or 5x10 to some power (i.e. 1, 10, 0.1, 200, 0.02, 5, 50) Examples: Right! Wrong!

60
Engineering 160 Steps in the Proper Construction of a Graph Log scale calibration: since log cycles are based on powers of 10 each cycle is printed with values 1 to 10. You need to only decide what power of 10 to apply to the first 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
Engineering 160 Steps in the Proper Construction of a Graph 4. Label axes Include: Name of the variable, the symbol, the unit e.g. Time, t, s 5. Plot points: Use a symbol around the data points; Lines don’t penetrate the symbols : - OR -

62
Engineering 160 Steps in the Proper Construction of a Graph 6. Draw curves 3 categories of data : y x y x y x ObservedTheoreticalExperimental

63
Steps in the Proper Construction of a Graph 7. Add plot title and key to identify curves if necessary Engineering 160

64
Example graph u Hand graph on log-log paper

65
Engineering 160 Graphing and Curve Fitting Part Two Lecture written by: Prof. Martha Selby Authored for presentation by: Julie Sandberg Date last updated: 6/ 23/ 98

66
Engineering 160 Graphical Analysis u Linear Function - Plot as a straight line on uniform grid (rectilinear) paper Y = mx + b u Exponential Function - Plot as straight line on semi log paper Y = be mx or ln Y = mx + ln b u Power Function - Plot as straight line on log-log paper Y = bx m or log Y = m log x + log b ln Y = m ln x + ln b

67
Engineering 160 Curve Fitting Methods Two methods for arriving at the “best-fit” straight line will be considered this semester: 1. Method of selected points 2. Method of least squares - linear regression (Discussed later - Chap. 8)

68
Engineering 160 Method of Selected Points u Plot data on the correct graph paper. u 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. u Choose two points on line (not 2 of the data points).

69
Engineering 160 Method of Selected Points: u Substitute points into equation and solve for m & b Y 1 = mX 1 + b Y 2 = mX 2 + b

70
Engineering 160 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 (X 1,Y 1 )Point B (X 2, Y 2 ) Power Function: Y = bx m Log form: log Y = m log x + log b (could use ln or log in equation) Solve: log Y 1 = m log X 1 + log b log Y 2 = m log X 2 + log b Find m and b (NOT log b)

71
Method of Selected Points for Exponential Functions Use the same procedure for Exponential Functions Y = be mx Log form: ln Y = mx + ln b (NOTE natural logs) Engineering 160

72
Statistics Lecture written by: Dr. Larry Genalo Authored for presentation by: Julie Sandberg Date last updated: 8/ 8/ 01

73
Engineering 160 Statistics Statistics - parameters calculated from sample observations (usually engineers deal with samples 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 = N i = 1 XiNXiN

74
Engineering 160 Variation Measures of Variation (scatter, dispersal) about the mean: Variance = S 2 = N i=1 (X i - X) 2 N - 1 Standard Deviation = S = S2S2 Note: this equation for variance (using N-1) is used for a small sample of a population

75
Engineering 160 Alternative Deviation Equation An alternative equation to find the standard deviation is the following: Standard Deviation = S =N (X i 2 ) - (Xi)2Xi)2 N (N-1)

76
Engineering 160 Example i XiXi Modes = 63 and 78 Median = (78+74) = 76 2 Mean = X = ( ) = Standard Deviation = S = 6( ) - ( ) 2 = (using the alternate equation) 6(5) Variance = S 2 = ( ) 2 = 119.1

77
Engineering 160 Example 2 i XiXi Freq of Occur. Grade Class Frequency Histogram Upper limit of grade ranges

78
Engineering 160 Frequency Distribution This can lead to a Continuous Distribution such as: XX - SX + S This is an example of a theoretical distribution called the Normal Distribution or a“Bell-shaped” curve. This is used when grading “on a curve” and also applies to many natural phenomena.

79
Engineering 160 Curve Fitting Given a set of data points “model” them with a curve which approximates their behavior. We’ll look only at a straight line fit: Linear Regression by the method of Least Squares.

80
Engineering 160 Curve Fitting Problem Y X What straight line is “best”? The problem: We know that a straight line has the form: Y = mX + b What values of m and b are the “best”?

81
Engineering 160 Curve Fitting Solution YpYp Y’ p XpXp Y X (X p, Y p ) Real data point Y’ p = mX p + b “Miss distance” Y p - Y’ p = Y p - (mX p + b)

82
Engineering 160 Curve Fitting Solution 2 Now calculate the sum of the squares of all “misses” Sum = (Y 1 - (mX 1 + b)) 2 + (Y 2 - (mX 2 + b)) (Y N - (mX N + b)) 2 Note: All X i and Y i are known. Calculus problem: Select m and b to minimize sum.

83
Engineering 160 Curve Fitting Solution 3 Calculating partial derivatives (Pardon?), setting them equal to zero and solving.

84
Engineering 160 Common Concern A Concern: Given any set of data points, we can find m and b. When is it a good idea to model with a straight line? ?

85
Engineering 160 Correlation Coefficient R = N i = 1 [(X i - X) (Y i - Y)] N i = 1 (X i - X) 2 N i = 1 (Y i - Y) 2 1/2 -1 R 1 R = 1perfect correlation R = 0totally uncorrelated R = -1meaning???

86
Engineering 160 Alternative R Note: An alternate equation for R is found as shown here... R = n (x i y i ) - (x i )(yi)yi) n(x i 2 ) - ( xi)2xi)2 n(y i 2 ) - ( yi)2yi)2

87
Engineering 160 Suggestions: Anytime you do a linear regression (or other types of curve-fitting) you should check the correlation coefficient (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 skill developed through experience. We can say: If R = 0.8, then 64% of the variance in the dependent variable is explainable by the variance in the independent variable. Note: R 2 = 0.64

88
Engineering 160 Nonlinear Graphs “Patterned” data not following a straight line? - Model with a curved line - Transform to a straight line model Power Curve

89
Nonlinear Graphs 2 Then, V = bT m logV = log b + m log T i.e., Let Y = log V and X = log T Now do a linear regression on the variables log T and log V. Note that the intercept derived is log b (NOT b). Engineering 160

90
Spreadsheets and MS Excel Part One Lecture written by: Dr. Larry Genalo Authored for presentation by: Julie Sandberg Date last updated: 6/ 24/ 98

91
Engineering 160 Spreadsheet This is a basic spreadsheet design.

92
Engineering 160 Parts of a Spreadsheet 1. Cell 2. Row 3. Column

93
Engineering 160 To enter data using MS Excel, type the information in the formula bar.

94
Engineering 160 Numerical Data Numerical Data to be used in calculations can be entered into the cells.

95
Engineering 160 Entering Numeric Data 1) Data being entered shows both in the formula bar and in the active cell.

96
Engineering 160 Entering Numerical Data 2) Depress the check mark or push either the Enter key or an arrow key to complete entering the data.

97
Engineering 160 Entering Numeric Data 3) Use either the mouse or the arrow keys to navigate to the next cell in which you wish to enter data.

98
Engineering 160 Text Text can be entered to create row and column headings within the spreadsheet.

99
Engineering 160 Entering Text To enter text, just type the text in the formula bar and enter it as you would for numbers.

100
Engineering 160 Entering Text To enter numerical values as text, type a single quote (‘) followed by the number.

101
Engineering 160 Formulas In Excel, formulas can be entered in cells to represent numerical values. There are two basic types of formulas: 1. Numeric Formulas 2. Reference Formulas To enter a formula, always begin with an equals sign (=), then proceed with the formula.

102
Engineering 160 Numeric Formulas A numeric formula in Excel is a mathematical expression that can be simplified to a single value independent of the values in any other cell.

103
Engineering 160 Numeric Formulas To enter numeric formulas, enter the formula in the formula bar. When it is entered, the formula will still be visible in the formula bar while the actual value will appear in the cell.

104
Engineering 160 Reference Formulas A Reference formula in Excel is a mathematical expression that contains references to other cells as variables.

105
Engineering 160References 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 specific cell within the spreadsheet. In MS Excel, these are denoted by putting a dollar sign ($) in front of both the column and row markers. For example, the cell A1 would be denoted as $A$1 in absolute reference. 2. Relative references are used to find cells relative to the formula cell. In MS Excel, they are denoted by using the column and row markers as they appear. For example, the cell A1 would be denoted as A1 in relative reference.

106
Engineering 160 Reference Formulas To enter reference formulas, enter the formula in the formula bar using references to cells containing data. When the formula is entered, the answer will appear in the cell, while the formula remains in the formula bar.

107
Engineering 160 Copying Formulas To copy a formula from an active cell, find the Copy command under the Edit menu. Highlight the area where the formula is to be copied. Find the Paste command under the Edit menu or if you wish to copy across a row or down a column select Edit-Fill after selecting the row or column. NOTE: Absolute and relative references will cause different results when copied, as demonstrated by the following examples.

108
Engineering 160 Absolute Reference Assume the following data has been entered in columns A and B. Given that the formula for D1 is =$A$1+$B$4, note what happens when it is copied to cells D2-D4.

109
Engineering 160 When the formula was copied, its references changed relative to the cell it was pasted in. Relative Reference Assume the same data has been entered in columns A and B. Given that the formula for D1 is =A1+B1, note what happens when it is copied to cells D2-D4.

110
Engineering 160 Function A function is a prewritten formula that performs an operation on given values and returns a value or values. It can be used alone or as a building block in a formula.

111
Engineering 160 Examples of MS Excel functions ACOS( ) - arccosineLN( ) - natural log ASIN( ) - arcsineLOG( ) - log, base 10 ATAN( ) - arctangentSIN( ) - sine AVERAGE( ) - averageSTDEV( ) - standard deviation COS( ) - cosineTAN( ) - tangent

112
Engineering 160 Using Functions When you have reached a point in a formula where you wish to insert a function, you can either enter the function name and arguments or you can use the Function Wizard.

113
Engineering 160 Using Functions The Function Wizard is a useful series of dialogue boxes that allow you to choose the function you desire from a complete list of Excel Functions and their descriptions. To access the Function Wizard, just click on the function key in the formula bar.

114
Engineering 160 Function Wizard Step 1 1) Choose the desired Function category 2) Choose the desired Function Name. (note the descriptions and form at the bottom) 3) Click OK to move on.

115
Engineering 160 Function Wizard Step 2 1) Enter the desired numerical value(s) or cell reference(s) as arguments. 2) Click the OK key

116
YES! We have a value for Pi. Engineering 160

117
Spreadsheets and MS Excel Part Two Spreadsheets and MS Excel Part Two Lecture written by: Dr. Larry Genalo Authored for presentation by: Julie Sandberg Date last updated: 6/ 25/ 98

118
Engineering 160 Graphing with MS Excel Creating graphs with MS Excel is a useful way to get a visual representation of collected data.

119
Engineering 160 Preparing Data u Make sure the column containing your independent variable is to the left. u This can be done by highlighting a column, cutting, and pasting. u Make sure your values for your independent variable are in increasing order. u 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! There are two things you can do to prepare your data that can make it much easier to create a graph:

120
Engineering 160 Graphing After you have prepared your data, Excel makes it simple to construct a graph. First, highlight your data. Then, click on the Chart Wizard icon.

121
Engineering 160 Graphing The Chart Wizard series of four dialogue boxes will appear prompting you for information about how you want your graph constructed.

122
Engineering 160 Example The following sequence of slides show how a chart might be constructed from the given data.

123
Engineering 160 Given Data

124
Engineering 160 Select Data Range

125
Engineering 160 Click Chart Wizard icon.

126
Engineering 160 Choose desired chart type. For most science and engineering applications relating two variables, the XY scatter option is most useful.

127
Engineering 160 Select chart subtype (format).

128
Engineering 160 Make sure data range is correct. Make selections based on how your data is entered in the spreadsheet.

129
Engineering 160 Enter labeling information.

130
Engineering 160 Select desired graph location.

131
Engineering 160 Result

132
Editing a Finished Graph After a graph has been constructed, it can be edited by clicking on its various parts or by using the chart toolbar. Engineering 160

133
Engineering Economy Lecture written by: Dr. Larry Genalo Authored for presentation by: Julie Sandberg Date last updated: 8/ 8/ 01

134
Engineering 160 Engineering Economy The following variables will be used throughout the presentation P = Present Sum (Cash Flow) F = Future Sum (Cash Flow) N = Number of Time Periods I = Interest Rate A = Equal Cash Flow Each Time Period

135
Engineering 160 Simple Interest Equation: F = P + N I P = P (1 + N I ) Example: If $ was deposited at 6% yearly interest, your account would have these balances after each year: YearBalance

136
Engineering 160 Compound Interest “Interest on the Accrued Interest” Equation: F = P (1+I) N Example: If $ was deposited at 6% interest and compounded annually, your account would have these balances after each year: Year BalanceEquation N01234 N (1.06) N.... P P(1+I) 1 P(1+I) 2 P(1+I) 3 P(1+I) 4 P(1+I) N....

137
Engineering 160 Compound Interest Time Line “Forward Time” Example: If you deposit $ today at 7% interest compounded annually, what will be the balance in 3 years? Solution: F = Future Value = P(1+I) N = $ ( ) 3 = $

138
Engineering 160 Compound Interest Time Line “Backward Time” Example: If $ is needed in 3 years, how much money should be deposited today, assuming 7% interest compounded yearly? Solution: P = Present Value = F(1+I) -N = $ (1+0.07) -3 = $

139
Engineering 160 Compound Interest Time Line “Backward Time” Example: If $ is needed in 3 years, how much money should be deposited today, assuming 7% yearly interest compounded quarterly? Solution: P = Present Value = F (1 + I/4) -N = $ ( /4) -12 = $

140
Engineering 160 Compound Interest Time Line “Backward Time” Example: If $ is needed in 3 years, how much money should be deposited today, assuming 7% yearly interest compounded quarterly? Solution: P = Present Value = F (1 + I/4) -N = $ (1+0.07/4) -12 = $ Compare: The answer where interest was compounded quarterly is less than the previous answer where interest was compounded yearly: Solution: P = Present Value = F (1 + I) -N = $ ( ) -3 = $

141
Engineering 160 Tips for Doing Problems When doing engineering economy problems, make sure: u “Time frames” match u If 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 12 u Answer is reasonable u Answer is rounded to the nearest penny

142
Engineering 160 Sinking Fund Definition: A sinking fund differs from compound interest in that we now have uniform payments over time in addition to the compounded interest. Solution: F = A + A(1+I) 1 + A(1+I) A(1+I) N-1 F = A (1+I) N - 1 I

143
Engineering 160 Sinking Fund Time Line Example: If you deposit $50 per month into an account that pays 6% interest, compounded monthly, for 2 years, how much is in the account immediately after the last deposit? Solution: F = Future Value = $50 = $ (1+ ) ( ) Example #1

144
Engineering 160 Sinking Fund Time Line Example #1 Example: If you deposit $50 per month into an account that pays 6% interest, compounded monthly, for 2 years, how much is in the account immediately after the last deposit? Please Note: Yearly interest in the equation is divided by 12 since payments are on a per-month basis. Also Note: There are 24 payments, not 23 months. Solution: F = Future Value = $50 = $ (1+ ) ( )

145
Engineering 160 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. Example #2

146
Engineering 160 Sinking Fund Time Line Example #2 Time Lines:

147
Engineering 160 Sinking Fund Time Line Example #2 Time Line: Solution: First, we find the future value of the money: F = Future Value = $2000 = $ ( )

148
Engineering 160 Sinking Fund Time Line Example #2 Time Line: Solution: Then, we find the present value of the money: P B = Present Value = F (1+I) -N = $ (1.08) -5 = $ Note: Since P A = $8000 > P B = $ , select plan A.

149
Engineering 160 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
Engineering 160 Sinking Fund Time Line Example #3 Old Time Line: New Time Line:

151
Engineering 160 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)

152
Engineering 160 Sinking Fund Time Line Example #3 New Time Line: Solution: Then, we find the present value of the money: P B = Present Value = F(1+I) -N = $ (1.08) -4 = $ Note: Since P A = $8000 < P C = $ , select plan C

153
Engineering 160 Annuity Note: Follow the algebraic steps used to find the present value of a sinking fund. This is the formula for an annuity. Solution: F = A Therefore: P = A (1+I) N - 1 I & P = F(1+I) -N (1+I) N - 1 I(1+I) N

154
Engineering 160 Annuity Application: The first application of the annuity formula is to find the present value of a sinking fund. The second is using the formula in situations like the following example. 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?

155
Engineering 160 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? Solution: = A A = $ (1+ ) (1+ ) $

156
Engineering 160 Summary Compound Interest Equation: F = P (1+I) N Time Line:

157
Engineering 160 Summary Sinking Fund Equation: F = A (1+I) N - 1 I Time Line:

158
Engineering 160 Summary Annuity Equation: P = A (1+I) N - 1 I(1+I) N Time Line:

159
Engineering 160 Amortization Table Definition: An amortization table is used to track monthly payments when repaying a loan. Example: If you take out a loan for $70,000 to be paid back in 30 years at a fixed yearly interest rate of 10.5%, what will be the amount of the monthly payment? Also create an amortization table for the first 12 months. [Taken from a table in an article by the Des Moines Register.] Solution: = A (1+ ) (1+ ) A = $ (monthly payment)

160
Engineering 160 Amortization Table Table: Payment Number Monthly Payment Amount for Interest Amount for Principal Current Balance To find Monthly Payment use the Annuity Formula = A A = $ (monthly payment) (1+ ) (1 + )

161
Engineering 160 Amortization Table Table: Payment Number Monthly Payment Amount for Interest Amount for Principal Current Balance Amount for Interest is found by multiplying the previous Current Balance by the monthly interest rate: AI = $70000 (0.105 / 12) AI = $612.50

162
Engineering 160 Amortization Table Table: Payment Number Monthly Payment Amount for Interest Amount for Principal Current Balance Amount for Principal is found by subtracting the Amount for Interest from the Monthly Payment: AP = $ $ AP = $27.82

163
Amortization Table Table: Payment Number Monthly Payment Amount for Interest Amount for Principal Current Balance Current Balance is found by subtracting the Amount for Principal from the previous Current Balance: CB = $ $27.82 CB = $ Engineering 160

164
Statics Lecture written by: Prof. Martha Selby Authored for presentation by: Julie Sandberg Date last updated: 8/ 8/ 01

165
Engineering 160 Mechanics The study of forces acting on bodies. 3 Branches of Mechanics: -Statics -Dynamics -Strength of Materials

166
Engineering 160 Statics The study of rigid bodies that are in equilibrium. Force A “push” or “pull” exerted by one body on another, such as: - a person pushing on a wall - gravity pulling on a person

167
Engineering 160 Scalar / Vector Scalar A quantity possessing only a magnitude. - mass, length, time Vector A quantity that has both a magnitude and direction. - velocity, force

168
Engineering 160 Force Force is a vector quantity, therefore a force is completely described by: 1) magnitude 2) direction 3) point of application 30º A 50 N

169
Engineering 160 Vectors Types of vectors used in statics: Coplanar vectors lie in the same plane. Colinear vectors act along the same line of action. Concurrent vectors have lines of action that pass through the same point.

170
Engineering 160 Vector Addition The parallelogram law A A B B A + B

171
Engineering 160 Resolution of forces into components The net effect of a number of forces on one point can be the same as the effect of one force. Fy Fx F (Fx) 2 + (Fy) 2 = F Fx = F cos Fy = F sin = tan -1 (Fy/Fx) F = (Fx 2 + Fy 2 ) 1/2

172
Engineering 160 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 = Fx 1 + Fx 2 + Fx ) Add all Y components. Ry = Fy 1 + Fy 2 + Fy ) Find resultant force, R R Rx Ry R = (Rx 2 + Ry 2 ) 1/2 = tan -1 (Ry/Rx)

173
Engineering 160 Example 30.0° 15.0° F 1 = 95.0 N F 1x F 1y F 2 = 62.0 N F 2x F 2y F 1x = 95.0 cos 30.0 = 82.3 N F 2x = 62.0 cos 15.0 = N Sum of F x = 22.4 N F 1y = 95.0 sin 30.0 = 47.5 N F 2y = 62.0 sin 15.0 = 16.1 N Sum of F y = 63.6 N

174
Engineering 160 Example 2 F 1x = 95.0 cos 30.0 = 82.3 N F 2x = 62.0 cos 15.0 = N Sum of F x = 22.4 N F 1y = 95.0 sin 30.0 = 47.5 N F 2y = 62.0 sin 15.0 = 16.1 N Sum of F y = 63.6 N F y = 63.6 N F = ? = ? F x = 22.4 N F = ( ) 1/2 = 67.4 N = tan -1 (63.6/22.4) = 71.3°

175
Engineering 160 A Moment The tendency of a force to cause rotation about a point. Moment = ( force magnitude ) ( ) Perpendicular distance from force’s line of action to the point. AA B R B = 1.5 m F = 10.0 N R A = 2.0 m M B = 10.0 N (1.5 m) = 15 Nm, direction is clockwise, CW M A = 10.0 N (2.0 m) = 20 Nm, direction is counterclockwise, CCW A

176
Engineering 160 Free Body Diagrams A free body diagram is a sketch of the body and all the forces 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
Engineering 160 Inclined Plane (no friction) Support removed Force normal to the plane

178
Engineering 160 Cable, Rope, or Chain Connector removedA tension force along the cable, away from the body.

179
Engineering 160 Roller or Simple Support Support removed Force perpendicular to the surface on which the roller could roll

180
Engineering 160 Pin or Hinge FxFx FyFy Pin removed Resultant force is at some unknown angle, so the X & Y components of the force are shown. The direction of the component forces are assumed and may be wrong.

181
Engineering 160 Equilibrium A body is in equilibrium if the sum of all the external forces and moments acting on the body are zero. 1) Fx = 0 2) Fy = 0 3) M = 0 (about any point)

182
Engineering 160 Steps in solving a statics problem. u Draw a free body diagram u Choose a reference frame. Orient the X & Y axes u (most often X is chosen in the horizontal direction and Y is chosen in the vertical direction.) u Choose a convenient point to calculate moments around. u (most often this will be at the pin connection) u Apply the 3 equilibrium equations and solve for the unknowns.

183
Engineering 160Example Problem Two children balance a see-saw in horizontal equilibrium. One weighs 80 pounds, and the other weighs 60 pounds and is sitting 4 ft from the fulcrum. Find the force the fulcrum applies to the beam and the distance from the fulcrum to the 80 lb child. (Neglect the mass of the see-saw.) Diagram X ft 4 ft 80 lbs60 lbs

184
Engineering 160 Example Free Body Diagram + y x X ft4 ft 80 lbs60 lbs F Solution F x = 0 = No X forces. F y = 0 = F F = 140 lbs + M fulcrum = 0 = 80 * X - 60 * 4 X = 3 ft

185
Engineering 160 Example kg 2.00 m 2.50 m 1.00 m 60.0º Neglect mass of beam m 70.0 (9.81) Cx C D Cy 2.50 m1.00 m D cos(60.0º) D sin(60.0º) Free Body Diagram X Y

186
Engineering 160 Example m 70.0 (9.81) Cx Cy 2.50 m1.00 m D cos(60.0º) D sin(60.0º) Fx = 0 = D cos(60.0) + Cx Fy = 0 = Cy (9.81) - D sin(60.0) Mc = 0 = 70.0(9.81)(2.50) - (D sin(60.0))(1.00) D = 1980 N C x = 991 N C y =2400 N C = (C x 2 + C y 2 ) 1/2 = 2600 N = tan -1 (C y /C x ) = 67.6º C Y X CxCx CyCy

187
Engineering 160 Example N 30.0º 300 N A B C D Beam Length = 8.00 m AB = 2.00 m BC = 2.00 m CD = 4.00 m Neglect mass of beam 150 N Ax Ay B Dy Dx X Y Free Body Diagram Ay = 300 cos 30.0 Ax = 300 sin 30.0 = 30.0º

188
Example 3 Solution Fx = 0 = -Dx sin(30.0) Fy = 0 = Dy B cos(30.0) M D = 0 = 150(4.00) - B(6.00) + (300 cos(30.0))(8.00) B = 446 N Dx = 150 N Dy = N (negative sign implies the wrong direction was assumed) Dx Dy D = ? = ? D = ( ) 1/2 = N = tan -1 (36.6/150) = 13.7º OR: 30.0º º = 16.3º D Engineering 160

189
Algorithms and Flowcharts Lecture written by: Prof. Martha Selby Authored for presentation by: Julie Sandberg Date last updated: 6/ 7/ 98

190
Engineering 160 FLOWCHARTING Preparation for Programming Remember, a computer is only a problem-solving tool! (one of the many different tools engineers use in solving problems)

191
Engineering 160 Engineering Method of Problem Solving: 1) Recognize and understand the problem 2) Accumulate facts 3) Select appropriate theory 4) Make necessary assumptions 5) Solve the problem 6) Verify results

192
Engineering 160 5) Solve the problem Performing this step may involve a computer 1) ………… 2) ………… 3) ………… 4) ………… 6)………… Engineering Method of Problem Solving:

193
Engineering 160 The 5 steps in using a computer as a problem - solving tool. a) Develop an Algorithm and a Flowchart b) Write the program in a computer language. (i.e.VBA, C) c) Enter the program into the computer. d) Test and debug the program e) Run the program, input data, and get the results from the computer.

194
Engineering 160 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
Engineering 160 Start / Stop Input / Output Process, Instruction Question, Decision (Use in Branching) Connector (connect one part of the flowchart to another) Comments, Explanations, Definitions Of the many symbols available, these 6 Basic Symbols will be used most: Flowchart Symbols

196
Engineering 160 Preparation (may be used with “counted loops”) Refers to Separate Flowchart (“Subprograms” are shown in separate flowcharts) Related to more advanced programming 2 Additional Symbols

197
Engineering 160 START Enter R and H Output R, H, V V= R 2 H STOP R = Radius of cylinder H = Height of cylinder V = Volume of cylinder A simple sequential structure: Given the radius and height for a cylinder, find the volume. Flowchart Examples

198
Engineering 160 Other Flowchart Examples Start Are you single? Under age 65? Claim dependents? Taxable income < 50,000? Can use Form 1040EZ Must use 1040A or 1040 Stop NO YES NO YES NO YES Use to determine what form to use to file Federal Income Tax Return

199
Engineering 160 Repetition / Looping Structure START Enter F Output F, C C = 5/9(F-32) Another Value ? STOP YES NO Input a temperature in Fahrenheit, F, and convert to Celsius, C

200
More Repetition / Looping Structures Engineering 160 Start Sum = 0 C = 0 Enter Exam Score, S Sum = Sum+S C = C+1 Is C = 25? Average = Sum / 25 Output Average Stop Calculate the average from 25 exam scores Sum = Total sum of exam scores C = Variable that keeps track of the number of exams added NOYES

201
Engineering 160 Introduction to Programming Concepts Using VBA Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

202
Engineering 160 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
Engineering 160 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 97 VBA 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
Engineering 160 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 VBA To create VBA programs (called macros), access the IDE: 1) Open Word or Excel 2) Access the Developer Tab→ Macros 3) 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
Engineering 160 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 using variables and constants

206
Engineering 160 What’s a Variable A 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
Engineering 160 Declaring Variables It is strongly recommended that you always declare your variables. This will help ensure your program runs correctly A variable declaration statement looks like this: Dim VariableName as datatype Examples: Dim Radius as Single, Area as Single Dim Count as Integer Dim StudentName as String

208
Engineering 160 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 precision Integer 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
Engineering 160 Mathematical operators (listed by order of precedence) ^Exponentiation -Negation * or /Multiplication or Division \Integer Division + or -Addition or Subtraction

210
Engineering 160 Assignment Statements VariableName = Expression The = 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
Engineering 160 Assignment Statements Cont’d. An Expression can be constant (a number or a literal value) Count = 3 UserName = “Martha Selby” An Expression can be another variable or a combination of values using operators Radius = 2 X = 5 Pi = 4*Atn(1) (Atn is a function that calculates the arctangent) Volume = Pi*Radius^2 X = Radius An Expression can also be a VBA function (we will cover some of these soon.)

212
Engineering 160 A Beginning VBA Program (a temperature conversion program) Note: We really need to know how to do both input and output to write any meaningful programs! Option Explicit Sub 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 here Fahrenheit = 212 Celsius = 5 / 9 * (Fahrenheit - 32) End Sub

213
Engineering 160 Input/Output Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

214
Engineering 160 Getting the Program to Communicate with the User Output (providing information to the user), using the Message Box function MsgBox(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
Engineering 160 Getting the Program to Communicate with the User cont’d 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
Engineering 160 The Temperature Conversion program revisited: The Temperature Conversion program revisited: Option Explicit Sub 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 here Fahrenheit = 212 Celsius = 5 / 9 * (Fahrenheit - 32) MsgBox ("For a fahrenheit temperature of " & Fahrenheit & " degrees.") MsgBox ("The celsius temperature = " & Celsius & " degrees.") End Sub

217
Engineering 160 The Temperature Conversion program revisited: Here are the message boxes from the previous program:

218
Engineering 160 Getting Input from the User Input (letting the user talk back to the program), using the Input Box function VariableName = InputBox(prompt) (The prompt is all that is required, but there are many other optional arguments available) Radius = InputBox(“Enter the radius of the circle in meters.”) The InputBox function is limited to retrieving a single piece of information from the user. The value that the user enters will be assigned to the variable on the left side of the = sign.

219
Engineering 160 The Temperature Conversion Program revisted: Option Explicit Sub MyFirstProgram() ' MyFirstProgram Macro ' Macro created 7/10/2003 by martha selby ‘ Dim Celsius As Single, Fahrenheit As Single Fahrenheit = 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
Engineering 160 The InputBox and MsgBox from the previous program: Input Box MsgBox

221
Engineering 160 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 and carriage-return characters in the prompt to cause the message to be continued 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
Engineering 160 Input/Output Part II Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

223
Engineering 160 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 filenumber Examples: Open (“U:\InputStuff.txt”) For Input as 1 Open (“U:\OutputStuff.txt”) For Output as 2 Mode 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
Engineering 160 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, varlist The filenumber should match the filenumber used in the Open For Input statement. The varlist should be a comma-delimited list of variables Examples: Open (“U:\InputStuff.txt”) For Input as 1 Input #1, x, y Close Always remember to close a file with a Close statement: Close [filenumber] (if filenumber is omitted all open files are closed)

225
Engineering 160 Example Program using Open and Input statements. Example Program using Open and Input statements. Option Explicit Sub Average() Dim Ave As Single, Exam1 As Single, Exam2 As Single Open (“U:\AverageIn.txt") For Input As 1 Input #1, Exam1 Input #1, Exam2 Ave = (Exam1 + Exam2) / 2 MsgBox ("The exam average = " & Ave) Close End Sub The contents of AverageIn.txt before program runs: You could have had one input statement: Input #1, Exam1, Exam

226
Engineering 160 Writing to an open file A new file will be created by the computer if a specified file doesn’t exit when opening in Output (or append) mode. To write to a file you have opened in Output mode you can use a Print or a Write statement. 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 with semicolons, or commas. If there is no outputlist an empty line is written to the file. Examples: Open (“U:\OutputStuff.txt”) For Output as 2 Print #2, “X = “; x; ” Y = “; y Close

227
Engineering 160 Program with Input and Print statements Program with Input and Print statements Option Explicit Sub Average() Dim Ave As Single, Exam1 As Single, Exam2 As Single Open (“U:\AverageIn.txt") For Input As 1 Open (“U:\AverageOut.txt") For Output As 2 Input #1, Exam1 Input #1, Exam2 Ave = (Exam1 + Exam2) / 2 Print #2, "The average of the exam scores = "; Ave Close End Sub The average of the exam scores = 85 The contents of the AverageOut.txt after the program runs:

228
Engineering 160 Writing to a file using a Write Statement 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 to the file. A Write # statement stores the data so that it can more easily read back from the file using the Input # statement. The Write # statement automatically places quotation marks around string data and delimits data fields with a comma. This makes it clear to the Input # statement where each data item begins and ends, and what type of data it is.

229
Engineering 160 Example program with Write statement Example program with Write statement Option Explicit Sub Students() Dim Name As String, IDnumber As Integer Open (“U:\StudentsOut.txt") For Output As 3 Name = InputBox("Enter a student's name.") IDnumber = InputBox("Enter last four digits of ID number.") Write #3, Name, IDnumber Close End Sub Contents of StudentsOut.txt file after program runs: "Martha Selby",4432

230
Engineering 160 Reading From a File Option Explicit Sub Students() Dim Name As String, IDnumber As Integer Open (“U:\StudentsOut.txt") For Input As 2 Input #2, Name, IDnumber MsgBox(“Student’s name: “ & Name & vbCrLf & “Student’s ID: “ & IDnumber) Close End Sub

231
Engineering 160 Let’s try it with a file created by a Print statement Let’s try it with a file created by a Print statement Option Explicit Sub Students() Dim Name As String, IDnumber As Integer Open (“U:\StudentsOut.txt") For Output As 3 Name = InputBox("Enter a student's name.") IDnumber = InputBox("Enter last four digits of ID number.") Print #3, Name, IDnumber Close End Sub Martha Selby 4432 Contents of StudentsOut.txt file after program runs:

232
Engineering 160 Read From a File Using a Print Statement Option Explicit Sub Students() Dim Name As String, IDnumber As Integer Open (“U:\StudentsOut.txt") For Input As 2 Input #2, Name, IDnumber MsgBox(“Student’s name: “ & Name & vbCrLf & “Student’s ID: “ & IDnumber) Close End Sub Now let’s read from the file we just wrote to with a Print statement. WE GET AN ERROR!

233
Engineering 160 Print # and Write # statements Print # statements are fine when you are creating a file that you just want to look at and/or print out (maybe Print is better for this since you don’t get the “ ” marks when you may not want them). Write # statements are best for outputting heavily structured data that then can be easily read and understood by an Input # statement later.

234
Engineering 160 Controlling the Flow Part 1: Decisions and Alternatives Lecture written by: Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

235
Engineering 160 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
Engineering 160 How do you compare things in VBA? 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

237
Engineering 160 Logical Condition (True or False questions) Comparison operators will be used to make logical expressions that have true or false answers: (Radius >= 5.0) (UserName = “Martha Selby”) ((A^2 + B^2) = 10)

238
Engineering 160 If Statement If Statement- A structure for making decisions and controlling the flow. We will look at a control structure called an If statement (a structure usually involves more than one programming statement and must be written 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 statement If ( logical condition) Then statement

239
Engineering 160 One Line If Statement cont’d One Line If Statement cont’d When an If Statement needs to execute only a single statement if the condition is true you can put the whole structure on one line (no End IF statement is required) If (X >= 0)Then Y=X ^ 0.5 If the logical condition is True the statement following the Then will be executed; if it’s False the statement will be ignored.

240
Engineering 160 If Statement cont’d The next form of the If Statement: The If … Then statement If ( logical Condition ) Then statement statement(s) End If

241
Engineering 160 If … Then Statement cont’d The computer decides if the condition is true and if so it executes the statements between the IF and the End IF. If (ExamScore >=90) Then MsgBox(“Congratulations, you got an A!”) LetterGrade = “A” End If Note: The use of consistent indentation and parenthesis is vital to writing good, understandable code!

242
Engineering 160 The next form of the If statement: If…Then…Else statement This structure lets the program chose between two alternative branches of code to execute. If (logical condition) Then Statement(s) … Else Statement(s) … End If

243
Engineering 160 If…Then…Else statement cont’d If…Then…Else statement cont’d If(a = 0) Then MsgBox(“No solution”) Else x = -b/a MsgBox(“X= “ & X) End If

244
Engineering 160 Getting More Complex More Than One Question to Ask: If…Then…ElseIf…Else statement You can have as many ElseIf statements as you want (to allow for as many branches as you want). The Else statement is optional If (logical condition 1) Then statement(s) 1 … ElseIf (logical condition 2) Then statement(s) 2 … Else statement(s) 3 … End If

245
Engineering 160 If-Then-Else if, Example Flowchart Is b 2 - 4ac < 0? Is b 2 - 4ac > 0? x = -b/2a Output x Output x1 and x2 “No Real Solution” x1 = -b + b 2 - 4ac 2a x2 = -b - b 2 - 4ac 2a YESNO YES NO See code on next slide

246
Engineering 160 Example If-Then-Else if Structure Example If-Then-Else if Structure If( b ^ * a * c < 0) Then MsgBox(“No real solution”) ElseIf (b ^ * a * c > 0)Then x1 = (- b + Sqr(b ^ * a * c)) / (2 * a) x2 = (- b - Sqr(b ^ * a * c) )/ (2 * a) MsgBox(“The real roots= “ & x1 & “ and “ & x2) Else x = -b / (2 * a) MsgBox(“The real root = “ & x) End If See previous slide for flowchart

247
Engineering 160 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
Engineering 160 Controlling the Flow Part 2: Loops Lecture written by: Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

249
Engineering 160 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: u A loop that repeats an indefinite number of times (in VBA, a DO …EXIT DO … LOOP ) u A loop that repeats a fixed number of times (in VBA, a FOR … NEXT loop)

250
Engineering 160 Using a Do… Exit Do… Loop Structure: Do statement(s) conditional exit using Exit Do statement (this can be anywhere inside the loop, but it should only be used once) Loop VBA 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
Engineering 160 Example Program with a Do Loop Option Explicit Sub MyFirstProgram() ' MyFirstProgram Macro ' Macro created 7/10/2003 by martha selby Dim Celsius As Single, Fahrenheit As Single Dim Answer As String Do Fahrenheit = 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 Do Loop End Sub

252
Engineering 160 Another program with a Do…Exit Do… Loop Option Explicit Sub SumIntegers() ' SumIntegers Macro ' Macro created 7/18/2003 by mselby Dim Sum As Integer, n As Integer Sum = 0 n = 1 Do If (n ^ 2 > 1000) Then Exit Do Sum = Sum + n n = n + 1 Loop MsgBox ("The final sum = " & Sum) End Sub

253
Engineering 160 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 counter Example: For i = 1 To 10 ‘ stepsize is 1 by default Sum = Sum + i Next i

254
Engineering 160 For…Next Loop Here’s what happens in a For.. Next loop: 1)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. 2)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
Engineering 160 For…Next Loop Example Option Explicit Sub Example() ‘ ' Macro created 9/30/2002 by Martha Selby ' Dim N as Integer, sum as Integer, J As Integer sum = 0 N = InputBox("Enter an positive integer number >= 3") For J = 1 To N Step 2 sum = sum + J Next J MsgBox ("The final sum =" & sum) End Sub What does this program do?

256
Engineering 160 For…Next Loop Example Flowcharts For…Next Loop Example Flowcharts

257
Engineering 160 Nesting Loops You 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 3 For n = 1 to 2 MsgBox(“j = “ & j & “ and n = “ & n) Next n Next j Results: j = 1 andn = 1 Note: The inside loop is executed j = 1 andn = 2 2 times for each of the 3 times j = 2 andn = 1 the outside loop executes. j = 2 andn = 2 j = 3 andn = 1 j = 3 andn = 2

258
Engineering 160 One-Dimensional Array Lecture written by: Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

259
Engineering 160 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
Engineering 160 One Dimensional Array Example (a list of numbers) One Dimensional Array Example (a list of numbers) A list of surefire lottery numbers, stored in an array named, Lotto Lotto(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, X 1, X 2, X 3, … X i

261
Engineering 160 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 Single Dim Lotto(1 to 10) as Integer These 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 elements that range from MyArray(0) to MyArray(5).

262
Engineering 160 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 Integer Lotto(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 way to do anything with multiple arrays elements is to use a For … Next loop ! For j = 1 to 6 Lotto(j) = InputBox(“Enter a lotto number”) Next j Note: The For.. Next loop variable is used for the array index, so the loop changes the value of the index each time through.

263
Engineering 160 Example Program The Program, finds the mean of array values and prints only the ones greater than mean. Option Explicit Sub Failure() Dim FailureTimes(1 To 10) As Single, MeanFailure As Single, Sum As Single Dim J As Integer Open (“U:\failure.dat") For Input As 1 Open (“U:\failure.out") For Output As 2 Sum = 0 For J = 1 To 10 Input #1, FailureTimes(J) Sum = Sum + FailureTimes(J) Next J MeanFailure = Sum / 10 Print #2, "The mean time to failure ="; MeanFailure Print #2, Print #2, " List of raliure times greater than the mean:" For J = 1 To 10 If (FailureTimes(J) > MeanFailure) Then Print #2, FailureTimes(J) Next J Close End Sub

264
Engineering 160 Array Functions There are many built-in array functions Lbound and Ubound are the names of array functions that let you find out the size of an array. ReDim is used to size an array that has been declared a dynamic array. The list goes on and on… You can discover others as you find a need for certain functions.

265
Engineering 160 Multi-Dimensional Arrays Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

266
Engineering 160 Multi-Dimensional Arrays Arrays can have multiple dimensions (meaning multiple subscripts). Multidimensional arrays in VBA can contain up to 60 dimensions! But don’t worry it’s extremely rare to use more than 2 or 3 dimensions. In Engr 160 we’re going to stick to two dimensions!

267
Engineering 160 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 String Dim X(5,6) as Integer A 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 each of the 31 columns could be a day in a month. You could assign a value to each position of the 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
Engineering 160 Two-Dimensional arrays cont. Since 2_D arrays have 2 subscripts they often take 2 nested For-Next Loops to manipulate them. Entering data into a 2-D array: For J = 1 to 12 For K = 1 to 31 Calendar(J,K) = InputBox(“Enter the correct day”) Next K Next J How can you tell in what order the Calendar array is filling the elements? Is it filling a month at a time? How could you change this?

269
Engineering D Array Example Problem 2-D Array Example Problem Find the average for each row and the overall average for the entire matrix X(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
Engineering 160 Example Program with 2-D arrays Option Explicit Sub Ave2D() Dim X(1 To 6, 1 To 4) As Single Dim RowAve(1 To 6) As Single, Sum As Single Dim Total As Single, TotAve As Single Dim J As Integer, K As Integer Open (“U:\AveIn.txt") For Input As 1 Open (“U:\AveOut.txt") For Output As 2 Total = 0 For K = 1 To 6 For J = 1 To 4 Input #1, X(K, J) Next J Next K For K = 1 To 6 Sum = 0 For J = 1 To 4 Sum = Sum + X(K, J) Total = Total + X(K, J) Next J RowAve(K) = Sum / 4 Next K TotAve = Total / 24 Print #2, "Overall average = " ; TotAve Print #2, For K = 1 To 6 Print #2, "The row #" ; K ; " average = " ; RowAve(K) Next K Close End Sub

271
Engineering 160 Functions – Using and Creating Lecture written by: Prof. Martha Selby Authored for presentation by: Emily Vereen Date last updated: Summer 2003

272
Engineering 160 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 a value by having the name of the function actually assigned a value. That means you send functions information and it does something and spits back a value. In VBA functions are essential and there are a huge variety of built-in functions already available.

273
Engineering 160 Built-in Functions Functions are available to do such things as manipulate string variables, format numbers, dates or times, and convert data from one format to another (also there’s the usual numeric functions) To use a function you need to know it’s name and it’s required arguments. You call or invoke a function from a sub procedure (or another function ) by using it’s name with the argument list. Name [, argumentlist] The argumentlist is a comma-delimited list of variables, arrays, or expressions to pass to the function. Note: The Name of the function will have the return value assigned to it.

274
Engineering 160 Built-in Function examples 1) Atn( numbervariable )returns the arctangent of numbervariable in radians 2) Exp( numbervariable )returns e raised to the power of numbervariable 3) FormatNumber( number [, DecimalPlaces ],returns number formatted to 2 decimal places as default or as many as you specify)

275
Engineering 160 Example program using built-in functions Option Explicit Sub ExampleFunctions() ' ExampleFunctions Macro ' Macro created 7/22/2003 by mselby Dim Pi As Single, NLog As Single Pi = 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 Sub

276
Engineering 160 Program Results: First MsgBox Second MsgBox Third MsgBox

277
Engineering 160 Creating Your own Functions A function is a type of program that can be used by another program. When called by another program a function will calculate and return a value (by having the Name take on a value) To create a function you use a Function Statement : Function NameYouPick(argumentlist [as type]) as type statement(s) NameYouPick = expression statement(s) End Function

278
Engineering 160 Example Function Function DeFunc(ByVal x as Integer, ByVal y as Integer) as Integer Dim z as Integer z = x + y DeFunc = x ^ z End Function

279
Engineering 160 Important Notes on Functions Arguments are values that VBA is to transfer, or pass, from one procedure to another. Within the Function that receives the arguments they act just like any other variables. You really should declare the type of each argument in the list ( as Single or as Integer, etc.). Notice the as type declaration after the (argumentlist). This is declaring the Function Name’s type. You must have a statement in the Function that assigns a value to the FunctionName. In the example it was: DeFunc = x ^ z To access or call a Function from another procedure, you simply use the Name of the Function with its argumentlist. ZSub = Defunc(3, 4) (this belongs in the calling program)

280
Engineering 160 Example Function and Calling Sub Procedure Example Function and Calling Sub Procedure Option Explicit Sub TestForSmog() Dim CarYear As Integer, ThisCar As String CarYear = InputBox("Enter the year of your car.") ThisCar = NeedsSmog(CarYear) If (ThisCar = "Yes") Then MsgBox ("Your car needs a smog check.") Else MsgBox ("Your car does not need a smog check.") End If End Sub Function NeedsSmog(ByVal CarYear As Integer) As String If (CarYear <= Year(Now) - 3) Then NeedsSmog = "Yes" Else NeedsSmog = "No" End If End Function

281
Engineering 160 Passing Arguments You can pass arguments into a procedure two different ways. The default method is by reference (ByRef). When an argument is passed by reference the recipient procedure gets access to the memory location where the original variable is stored and can change the original variable. The other method is by value (ByVal). When an argument is passed by value the recipient procedure gets only a copy of the information in the variable and can’t change the original.

282
Engineering 160 Example of passing by default (ByRef) Example of passing by default (ByRef) Option Explicit Sub DeSub() ' DeSub Macro ' Macro created 7/28/2003 by mselby Dim ZSub As Integer, XSub As Integer, YSub As Integer XSub = 3 YSub = 4 ZSub = DeFunc(XSub, YSub) MsgBox ("ZSub =" & ZSub & vbCrLf & "XSub = " & XSub & _ vbCrLf & "YSub =" & YSub) End Sub Function DeFunc(ByRef x As Integer, ByRef y As Integer) As Integer Dim z As Integer z = x + y DeFunc = x ^ z x = 15 y = 20 End Function

283
Engineering 160 Example of passing by value (ByVal) Example of passing by value (ByVal) Option Explicit Sub DeSub() ' DeSub Macro ' Macro created 7/28/2003 by mselby Dim ZSub As Integer, XSub As Integer, YSub As Integer XSub = 3 YSub = 4 ZSub = DeFunc(XSub, YSub) MsgBox ("ZSub =" & ZSub & vbCrLf & "XSub = " & XSub & _ vbCrLf & "YSub =" & YSub) End Sub Function DeFunc(ByVal x As Integer, ByVal y As Integer) As Integer Dim z As Integer z = x + y DeFunc = x ^ z x = 15 y = 20 End Function

284
Engineering 160 Subprogram as Subs or Subroutines Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

285
Engineering 160 Subprograms Subprograms can be Functions or Subs (subroutines) There are several advantages to splitting your large program 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 another Procedure 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
Engineering 160 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 a Function and a Sub is that a Sub does not have a value associated with it’s name, and it is accessed using a Call statement

287
Engineering 160 Example of a Sub (or subroutine) as a subprogram. Example of a Sub (or subroutine) as a subprogram. Option Explicit Sub Main() ' Main Macro Dim R As Single, Theta As Single, X As Single, Y As Single R = 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 Sub Sub 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) End Sub

288
Engineering 160 Returning values from a Sub In a Sub procedure that is accessed from another procedure, the way values can be returned is through the argument list (No value is ever associated with the Sub ’s name). You can think of some of the variables in an argument list as passing values in to the sub and some as passing values out of the Sub. How does this affect the use of ByVal and ByRef in the argument list?

289
Engineering 160 Example Revised using ByVal for passing arguments: Option Explicit Sub Main() ' Main Macro ' Macro created 7/30/03 by mselby Dim R As Single, Theta As Single, X As Single, Y As Single R = 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 Sub Sub 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) End Sub Note the answers are WRONG!

290
Engineering 160 Example Revised with mixed ByVal and ByRef for passing arguments Option Explicit Sub Main() ' Main Macro ' Macro created 7/30/03 by mselby Dim R As Single, Theta As Single, X As Single, Y As Single R = 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 Sub Sub 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) End Sub Note the answers are Correct! This is the same as the first example.

291
Engineering 160 Final words on ByVal vs. ByRef Remember: Arguments bringing in values that you don’t want changed in the subprogram should be passed ByVal; since ByVal passes only a copy of the value and the original value in the main program will not be changed.

292
Engineering 160 Subprograms with Arrays Lecture written by: Prof. Martha Selby Authored for presentation by: Emily Vereen Date last updated: Summer 2003

293
Engineering 160 Subprograms (a Functions or a Subs) with Arrays as arguments To pass a whole array to a subprogram use the array name in the argument list followed by empty parentheses. Call MySub(MyArray(), Radius, Volume) Also Arrays must be passed ByRef only!

294
Engineering 160 Example using a Sub with arrays Option Explicit Sub Ave2D() Dim X(1 To 6, 1 To 4) As Single, Total As Single Dim TotAve As Single Dim J As Integer, K As Integer Open (“U:\AveIn.txt") For Input As 1 Open (“U:\AveOut.txt") For Output As 2 Total = 0 For K = 1 To 6 For J = 1 To 4 Input #1, X(K, J) Next J Next K Call CalAve(X(), Total) TotAve = Total / 24 Print #2, "Overall average = " & TotAve Close End Sub Sub CalAve(ByRef X() As Single, ByRef Total As Single) Dim K As Integer, J As Integer For K = 1 To 6 For J = 1 To 4 Total = Total + X(K, J) Next J Next K End Sub

295
Engineering 160 Example program, finds largest in a table of values. Example program, finds largest in a table of values. Option Explicit Sub Large() Dim Table(1 to 4, 1 to 3) As Single, Big As Single Dim L As Integer, M As Integer Open (“U:\largest.dat") For Input As 1 Open (“U:\Largest.out") For Output As 2 For L = 1 To 4 For M = 1To 3 Input #1, Table(L, M) Next M Next L For L = 1 To 4 For M = 1 To 3 Print #2, Table(L, M), ‘note, end of line prints all values from inner loop on 1 line Next M Print #2, vbCr ‘note this is a carriage return, to go to a new print line Next L Big = Largest(Table()) Print #2, Print #2, "The largest value = " & Big Close End Sub Function Largest(ByRef Table() As Single) As Single Dim H As Integer, J As Integer Largest = Table(0, 0) For H = 1 To 4 For J = 1 To 3 If (Table(H, J) > Largest) Then Largest = Table(H, J) Next J Next H End Function The largest value = 55 Largest.out file contents:

296
Engineering 160 Excel VBA Programming Lecture written by: Prof. Martha Selby Authored for presentation by: Emily Vereen Date last updated: Summer 2003

297
Engineering 160 VBA and Objects VBA 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 an external stimulus). The notation used is a dot notation with a left to right hierarchy. ActiveSheet.Range(“A1”).Font.Bold = True The above is of the form of object.object.object.property = value What do you think that statement does?

298
Engineering 160 Working with cells and ranges in an Excel worksheet Working with cells and ranges in an Excel worksheet Excel uses what’s called A1 notation for cell addresses, (column letter and row number). But you’ll also see R1C1 notation (row number and column number), which can be confusing! Cell B3 would be R3C2.

299
Engineering 160 The Range Object The 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 value from 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”).Value To put a value stored in a variable or the result of an expression into a cell: Range(“A1”).Value = VariableName or expression Examples: Range(“A1:B10”).Value = 2 StudentName = Range(“E3”).Value

300
Engineering 160 The Cells Object The Cells Object Another way to reference a range is to use to use Cells (no there is no such thing as Cell) Cells(rowIndex, columnIndex), this is like the R1C1 notation Cells(3,2).Value = 5‘this assigns the number 5 to Cell B3

301
Engineering 160 Active Cell The 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 property You 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 expression To move the active cell – use the Select method. Range(“C3”).Select‘now cell C3 is the active cell Cells(5,12).Select‘now cell L5 is the active cell

302
Engineering 160 Active Cell cont. Another way to move the active cell is in a relative sense, using the Offset property. ActiveCell.Offset(rowOffset, columnOffset).Select Positive 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
Engineering 160 Example Excel Program Option Explicit Sub CellDataDemo() Dim radius As Single, i As Integer Range("B2").Select 'Moving active cell to B2 For i = 1 To 3 radius = ActiveCell.Value ActiveCell.Offset(0, 1).Select ActiveCell.Value = 4 / 3 * (4 * Atn(1)) * radius ^ 3 ActiveCell.Offset(0, 1).Select ActiveCell.Value = 4 * (4 * Atn(1)) * radius ^ 2 ActiveCell.Offset(1, -2).Select Next i End Sub

304
Engineering 160 Excel WorkSheet from last program. Excel WorkSheet from last program. Excel VBA Demo:Radius, mVolume, m^3Surface Area, m^ Before program execution: Excel VBA Demo:Radius, mVolume, m^3Surface Area, m^ After program execution:

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google