Download presentation

Presentation is loading. Please wait.

Published byRicardo Claycomb Modified over 2 years ago

1
**ENGINEERING 160 Exit VBA Lessons: Class Introduction**

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 Engineering Problem Solving Lessons: Problem Presentation in Engineering Dimensions and Units Estimation Analysis in Design Graphing and Curve Fitting Part One Part Two Statistics Spreadsheets and MS Excel Engineering Economy Statics Excel VBA Programming Copyright, Iowa State University Exit

2
**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
**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) Grading Instructor’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 160 More Course Objectives To 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 Sobek Authored for presentation by: Julie Sandberg Date 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 assumptions Select 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 rules apply only to handwritten work) 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) Course No. Pg Due Date Name Problem 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. 1 Name Due Date Problem Nos. 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
**Physical Problem Layout 2:**

Course No. 2 Name Due Date Problem Nos. 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
**Physical Problem Layout 3:**

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

15
**Physical Problem Layout 4:**

Engineering 160 2 Sobek, Mark 1/21/01 Example 1 2 Theory: V = (/4)D2H 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) = (105) ft3 = (105) ( L/ft3) = 7.12 (105) L m = (1 kg/L)(7.12 (105) L) = 7.12 (105) kg

16
**Physical Problem Layout 5:**

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

17
**Physical Problem Layout 6:**

Engineering 160 2 Sobek, Mark 1/21/01 Example 2 3 Theory: Apply the Law of Cosines to RST: RT = [RS2 + ST2 - 2(RS)(ST)cos(RST)]1/2 Apply 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)

18
**Physical Problem Layout 7:**

Engineering 160 Physical Problem Layout 7: Engineering 160 3 1/21/01 Sobek, Mark Example 2 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 AreaRSTU = (1/2)(120)(90)sin(115º) +(1/2)(130)(101)sin(100º) = m2 Exit

19
**Dimensions and Units Lecture written by: Dr. James Hilliard**

Authored for presentation by: Julie Sandberg Date last updated: 6/16/98

20
**Example: Consider the following mechanical system:**

Z Motion Path Velocity Mass Y X 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
**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. Physical Quantity Unit A = (N) (U) Numerical Value

22
**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
**Example: V = L / T 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
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” 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 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
**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**

Thermodynamic Temperature Amount of a Substance Luminous Intensity Meter Kilogram Second Ampere Kelvin Mole Candela m kg s A K mol cd

29
**Supplementary Units: Quantity Name Symbol Plane angle Solid angle**

Radian Steradian rad sr

30
Example: The density of water at 50ºF is about 1.94 slug/ft3. 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 = R2 H = (25.0 ft) ft ( m)3 ft3 = 1946 = 1.95 x 103 m3 Mass = (Vol)(Density) = (25.0 ft) ft slug kg ft3 slug = 1.95 x 106 kg 50.0 ft 35.0 ft

31
**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
**Significant Figures writing a number, except those used to define only**

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. 0.0015, , ETC.

33
**Rules for Handling Significant Figures**

Rounding Numbers Multiplication Rules (Division Rules) Addition Rules (Subtraction Rules)

34
Rounding Numbers If 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.

36
**Example (Rules for Addition or Subtraction)**

37
**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 Example (Proper Use of Significant Figures) Convert miles to kilometers: 10.00 miles km mile = km Thus, the final answer (16.09 km) contains 4 significant figures just like the miles did. Exit

39
**Estimation Lecture written by: Dr. James Hilliard**

Authored for presentation by: Julie Sandberg Date last updated: 6/ 18/ 98

40
**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
**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
**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
**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
**Estimation Format Example**

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

45
**Example cont. Exit 2 2 Theory: Vol = (Length)()(Radius)2**

Engineering 160 Example cont. Engineering 160 2 Sobek, Mark Example 2 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 mm3 ~ 4000 mm3 Exit

46
**Analysis in Design Lecture written by: Dr. James Hilliard**

Authored for presentation by: Julie Sandberg Date last updated: 6/ 18/ 98

47
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: Repeated Analysis...

48
**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
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
Example Problem Cable H Pin

51
**Example cont. Free Body Diagram Governing Equations:**

1. ß = ARCTAN[(L sin - 2H)/L cos ] 2. Ax = T cos ß 3. Ay = T sin ß + Mg 4. A = (Ax2 + Ay2)1/2 5. T = (2 Mg cos )/(cos ß sin - sin ß cos ) ß Mg T L H Ax Ay

52
**Table of Values (Degrees) T (Newtons) A (Newtons) 10 20 30 40 50 60**

70 80 495474 461638 427462 394030 362702 335145 313294 299105 483056 463994 449397 433850 419967 408359 399590 394098

53
**Crane Data Graph Exit BOOM ANGLE (degrees) 500000 450000 A 400000 T**

Engineering 160 Crane Data Graph P I N & C A B L E O D (N) 500000 450000 A 400000 T 350000 300000 250000 10 20 30 40 50 60 70 80 BOOM ANGLE (degrees) Exit

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
**Representation of Technical Data**

Experimental Process Steps: Collecting data Recording and presenting data Tabular form Graphical form Data analysis Identification of equation showing functional relationships

56
**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
**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. Ordinate, y axis Dependent variable Abscissa, x axis Independent variable

58
**Steps in the Proper Construction of a Graph**

3. Calibrate the axes: Assign numerical values to the graduations Graduation 10 20 Calibration

59
**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! 2 4 6 8 Wrong! 2 4 6 8

60
**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
**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
**Steps in the Proper Construction of a Graph**

6. Draw curves 3 categories of data: Observed Theoretical Experimental y y y x x x

63
**Steps in the Proper Construction of a Graph**

Engineering 160 Add plot title and key to identify curves if necessary Exit

64
Example graph Hand graph on log-log paper

65
**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
**Graphical Analysis Linear Function - Exponential Function -**

Plot as a straight line on uniform grid (rectilinear) paper Y = mx + b Exponential Function - Plot as straight line on semi log paper Y = bemx or ln Y = mx + ln b Power Function - Plot as straight line on log-log paper Y = bxm or log Y = m log x + log b ln Y = m ln x + ln b

67
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
**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 & b Y1 = mX1 + b Y2 = 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 = bxm Log form: log Y = m log x + log b (could use ln or log in equation) Solve: log Y1 = m log X1 + log b log Y2 = m log X2 + log b Find m and b (NOT log b)

71
**Method of Selected Points for Exponential Functions**

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

72
**Statistics Lecture written by: Dr. Larry Genalo**

Authored for presentation by: Julie Sandberg Date last updated: 8/ 8/ 01

73
**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 Xi N i = 1

74
**Variation Variance = S2 =**

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

75
**Alternative Deviation Equation**

An alternative equation to find the standard deviation is the following: Standard Deviation = S = N (Xi2) - ( Xi)2 N (N-1)

76
Example i 1 2 3 4 5 6 Xi 92 63 74 63 78 78 Modes = 63 and 78 Median = (78+74) = 76 2 Mean = X = ( ) = 74.67 6 Standard Deviation = S = ( ) - ( ) = 10.91 (using the alternate equation) (5) Variance = S2 = ( )2 = 119.1

77
Example 2 i 1 2 3 ... 48 Xi 85 93 72 ... 5 Histogram Freq of Occur. Grade Class 15 10 8 13 15 4 0 - 59 Frequency 5 Upper limit of grade ranges

78
**Frequency Distribution**

This can lead to a Continuous Distribution such as: X - S X X + 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
**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
**Curve Fitting Problem Y What straight line is “best”? X**

The problem: We know that a straight line has the form: Y = mX + b What values of m and b are the “best”?

81
**Curve Fitting Solution**

Yp Y’p Y Xp X (Xp, Yp) Real data point Y’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))2 Note: All Xi and Yi are known. Calculus problem: Select m and b to minimize sum.

83
**Curve Fitting Solution 3**

Calculating partial derivatives (Pardon?), setting them 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 model with a straight line? ?

85
**Correlation Coefficient**

[(Xi - X) (Yi - Y)] i = 1 R = N N 1/2 (Xi - X)2 (Yi - Y)2 i = 1 i = 1 R = 1 perfect correlation R = 0 totally uncorrelated R = -1 meaning??? -1 R 1

86
**Note: An alternate equation for**

Alternative R Note: An alternate equation for R is found as shown here... n ( xiyi) - ( xi)( yi) R = n( xi2) - ( xi)2 n( yi2) - ( yi)2

87
**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: R2 = 0.64

88
**Nonlinear Graphs “Patterned” data not following a straight line? Power**

- Model with a curved line - Transform to a straight line model Power Curve

89
**Nonlinear Graphs 2 Exit Then, V = bTm logV = log b + m log T**

Engineering 160 Nonlinear Graphs 2 Then, V = bTm 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). Exit

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
Spreadsheet This is a basic spreadsheet design.

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

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 Data 1) Data being entered shows both in the formula bar and in the active cell.

96
**Entering Numerical Data**

2) Depress the check mark or push either the Enter key or an arrow key to complete entering the data.

97
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
Text Text can be entered to create row and column headings within the spreadsheet.

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

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

101
**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
**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
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
**Reference Formulas A Reference formula in Excel is a mathematical**

expression that contains references to other cells 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 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
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
**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
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
**Assume the same data has been entered in **

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
**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
**Examples of MS Excel functions**

ACOS( ) - arccosine LN( ) - natural log ASIN( ) - arcsine LOG( ) - log, base 10 ATAN( ) - arctangent SIN( ) - sine AVERAGE( ) - average STDEV( ) - standard deviation COS( ) - cosine TAN( ) - tangent

112
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
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
**Function Wizard Step 1 1) Choose the desired Function category**

Function Name. (note the descriptions and form at the bottom) 3) Click OK to move on.

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

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

117
**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
**Graphing with MS Excel Creating graphs with MS Excel**

is a useful way to get a visual representation 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
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
Graphing The Chart Wizard series of four dialogue boxes will appear prompting you for information about how you want your graph constructed.

122
**Example The following sequence of slides show**

how a chart might be constructed from the given data.

123
Given Data

124
Select Data Range

125
Click Chart Wizard icon.

126
**Choose desired chart type.**

For most science and engineering applications relating two variables, the XY scatter option is most useful.

127
Select chart subtype (format).

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

129
**Enter labeling information.**

130
**Select desired graph location.**

131
Result

132
**Editing a Finished Graph**

Engineering 160 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. Exit

133
**Engineering Economy Lecture written by: Dr. Larry Genalo**

Authored for presentation by: Julie Sandberg Date last updated: 8/ 8/ 01

134
**Engineering Economy P = Present Sum (Cash Flow)**

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
**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: Year Balance

136
**Compound Interest Equation: F = P (1+I)N**

“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 Balance Equation 1 2 3 4 N 100.00 106.00 112.36 119.10 126.25 100 (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
**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
**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
**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
**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
**Tips for Doing Problems**

When doing engineering economy problems, make sure: “Time frames” match 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 Answer is reasonable Answer is rounded to the nearest penny

142
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 (1+I)N - 1 F = A I

143
**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? ( )24 - 1 0.06 12 Solution: F = Future Value = $50 = $ ( ) 0.06 12

144
**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. ( )24 - 1 0.06 12 Solution: F = Future Value = $50 = $ ( ) 0.06 12

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.

146
Sinking Fund Time Line Example #2 Time Lines:

147
**Sinking Fund Time Line Example #2 Time Line:**

Solution: First, we find the future value of the money: F = Future Value = $2000 = $ ( )5 - 1 0.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 Line Example #3 Old 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 - 1 0.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 - 1 I Solution: F = A & P = F(1+I)-N Therefore: P = A (1+I)N - 1 I(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 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
**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? $15000 45 46 47 48 (1+ )48 - 1 (1+ )48 0.07 12 Solution: = A A = $359.19 0.07 12 0.07 12

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

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

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

159
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.] ( ) ( )360 0.105 12 Solution: = A 0.105 12 0.105 12 A = $ (monthly payment)

160
**Amortization Table Table: (1+ )360 - 1 (1 + )360 70000 = A**

Payment Number Monthly Payment Amount for Interest Amount for Principal Current Balance ( ) ( )360 To find Monthly Payment use the Annuity Formula 0.105 12 70000 = A 0.105 12 0.105 12 A = $ (monthly payment)

161
**Amortization Table Table: AI = $70000 (0.105 / 12) AI = $612.50**

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
**Amortization Table Table: AP = $640.32 - $612.50 AP = $27.82**

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 = $ $612.50 AP = $27.82

163
**Amortization Table Exit Table: CB = $70000 - $27.82 CB = $69972.18**

Engineering 160 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 = $ Exit

164
**Statics Lecture written by: Prof. Martha Selby**

Authored for presentation by: Julie Sandberg Date 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, time Vector A 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) magnitude 2) direction 3) point of application 50 N A 30º

169
**Vectors Types of vectors used in statics: Concurrent vectors have**

Coplanar vectors lie in the same plane. Concurrent vectors have lines of action that pass through the same point. Colinear vectors act along the same line of action.

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

171
**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. Fx = F cos Fy = F sin = tan-1 (Fy/Fx) F = (Fx2 + Fy2)1/2 F Fy Fy Fx (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 + Fx 3) Add all Y components. Ry = Fy1 + Fy2 + Fy 4) Find resultant force, R R = (Rx2 + Ry2)1/2 = tan-1(Ry/Rx) R Ry Rx

173
**Example F1y = 95.0 sin 30.0 = 47.5 N F1x = 95.0 cos 30.0 = 82.3 N**

F1 = 95.0 N F1y F2 = 62.0 N 30.0° F2y 15.0° F2x F1x F1x = 95.0 cos 30.0 = N F2x = 62.0 cos 15.0 = N Sum of Fx = N F1y = 95.0 sin 30.0 = 47.5 N F2y = 62.0 sin 15.0 = 16.1 N Sum 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 = N F1y = 95.0 sin 30.0 = 47.5 N F2y = 62.0 sin 15.0 = 16.1 N Sum of Fy = N Fy = 63.6 N F = ? 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’s line of action to the point. AA F = 10.0 N A RB = 1.5 m RA = 2.0 m B MB = 10.0 N (1.5 m) = 15 Nm, direction is clockwise, CW MA = 10.0 N (2.0 m) = 20 Nm, direction is counterclockwise, CCW

176
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
**Inclined Plane (no friction)**

Support removed Force normal to the plane

178
**A tension force along the**

Cable, Rope, or Chain Connector removed A tension force along the cable, away from the body.

179
**Roller or Simple Support**

Support removed Force perpendicular to the surface on which the roller could roll

180
**force are shown. The direction of the component forces are assumed and**

Pin or Hinge Pin removed Fx Fy 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
**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
**Steps in solving a statics problem.**

Draw a free body diagram Choose 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 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 80 lbs 60 lbs X ft 4 ft

184
**Example Free Body Diagram F Solution Fx = 0 = No X forces.**

80 lbs 60 lbs + x X ft 4 ft F Solution Fx = 0 = No X forces. Fy = 0 = F F = 140 lbs Mfulcrum = 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 m 1.00 m Free Body Diagram 2.00 m 70.0 (9.81) D cos(60.0º) Y Cx Cy X D sin(60.0º) 2.50 m 1.00 m

186
**Example 2 Fx = 0 = D cos(60.0) + Cx**

70.0 (9.81) D cos(60.0º) Y Cx Cy D sin(60.0º) 2.50 m 1.00 m X 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 Cx = 991 N Cy =2400 N C C = (Cx2 + Cy2)1/2 = 2600 N = tan-1(Cy/Cx) = 67.6º Cy Cx

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 m AB = 2.00 m BC = 2.00 m CD = 4.00 m Neglect mass of beam A 150 N B C 300 N D 30.0º Free Body Diagram 150 N Ay Ax Y B Ay = 300 cos 30.0 Ax = 300 sin 30.0 = 30.0º X Dx Dy

188
**Example 3 Solution Exit Fx = 0 = -Dx + 300 sin(30.0)**

Engineering 160 Example 3 Solution Fx = 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 N Dx = 150 N Dy = N (negative sign implies the wrong direction was assumed) Dx = ? D = ? Dy OR: 30.0º º = 16.3º D = ( )1/2 = N = tan-1(36.6/150) = 13.7º D Exit

189
**Algorithms and Flowcharts**

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

190
**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 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
**Performing this step may involve a computer**

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

193
**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
**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 / Stop Connector (connect one part of the flowchart to another) Input / Output Comments, Explanations, Definitions Process, 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**

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

198
**Other Flowchart Examples**

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

199
**Repetition / Looping Structure**

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

200
**More Repetition / Looping Structures**

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

201
**Introduction to Programming Concepts Using VBA**

Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date 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 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
**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 ) 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
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
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
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
**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
**Mathematical operators (listed by order of precedence)**

^ Exponentiation - Negation * or / Multiplication or Division \ Integer Division + or - Addition or Subtraction

210
**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
**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
**A Beginning VBA Program (a temperature conversion program)**

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 Note: 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 Vereen Date last updated: Summer 2003

214
**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
**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 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
**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 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
**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
**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 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
**Input/Output Part II Lecture written by: Prof. Martha Selby**

Updated for presentation by: Emily Vereen Date 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 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
**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
**Example Program using Open and Input statements.**

The contents of AverageIn.txt before program runs: 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 90 80 You could have had one input statement: Input #1, Exam1, Exam2

226
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
**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 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 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
**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
**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
**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 Contents 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 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 WE GET AN ERROR!

233
**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
**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
**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: Operator Meaning = 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 expressions that 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 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
**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
**The next form of the If Statement:**

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
**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
**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 End If

243
**If…Then…Else statement cont’d**

If(a = 0) Then MsgBox(“No solution”) Else x = -b/a MsgBox(“X= “ & X) End If

244
**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
**If-Then-Else if, Example Flowchart**

Is b2 - 4ac < 0? YES NO Is b2 - 4ac > 0? NO YES x1 = -b + b2 - 4ac 2a “No Real Solution” x = -b/2a x2 = -b b2 - 4ac 2a Output x Output x1 and x2 See code on next slide

246
**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
**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: AND Conjunction (only if both sub expressions are true it is True) OR Disjunction (if either or both sub expressions is true it is True) NOT Negation

248
**Controlling the Flow Part 2: Loops**

Lecture written by: Martha Selby Updated for presentation by: Emily Vereen Date 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: 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
**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
**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
**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 ‘ stepsize is 1 by default Sum = Sum + i Next 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 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
**For…Next Loop Example Flowcharts**

257
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 and n = 1 Note: The inside loop is executed j = 1 and n = times for each of the 3 times j = 2 and n = 1 the outside loop executes. j = 2 and n = 2 j = 3 and n = 1 j = 3 and n = 2

258
**One-Dimensional Array**

Lecture written by: Martha Selby Updated for presentation by: Emily Vereen Date 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, 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, 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 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
**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
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:" If (FailureTimes(J) > MeanFailure) Then Print #2, FailureTimes(J) Close End Sub

264
**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
**Multi-Dimensional Arrays**

Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

266
**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
**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
**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
**2-D Array Example Problem**

Find the average for each row and the overall 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
**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 Sum = 0 Sum = Sum + X(K, J) Total = Total + X(K, J) RowAve(K) = Sum / 4 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
**Functions – Using and Creating**

Lecture written by: Prof. Martha Selby Authored for presentation by: Emily Vereen Date 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 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
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
**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
**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 Exit

276
Program Results: First MsgBox Second MsgBox Third MsgBox

277
**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 End Function

278
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
**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
**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" NeedsSmog = "No" End Function

281
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
**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
**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
**Subprogram as Subs or Subroutines**

Lecture written by: Prof. Martha Selby Updated for presentation by: Emily Vereen Date last updated: Summer 2003

285
**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
**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
**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)

288
**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
**Example Revised using ByVal for passing arguments:**

Note the answers are WRONG! 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)

290
**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) 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 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
**Subprograms with Arrays**

Lecture written by: Prof. Martha Selby Authored for presentation by: Emily Vereen Date 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 array name in the argument list followed by empty parentheses. Call MySub(MyArray(), Radius, Volume) Also Arrays must be passed ByRef only!

294
**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
**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 M = 1 To 3 Print #2, Table(L, M), ‘note , end of line prints all values from inner loop on 1 line Print #2, vbCr ‘note this is a carriage return, to go to a new print line 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 Largest.out file contents: The largest value = 55

296
**Excel VBA Programming Lecture written by: Prof. Martha Selby**

Authored for presentation by: Emily Vereen Date last updated: Summer 2003

297
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
**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
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
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
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
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
**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.Value = 4 * (4 * Atn(1)) * radius ^ 2 ActiveCell.Offset(1, -2).Select Next i End Sub

304
**Excel WorkSheet from last program.**

Before program execution: Excel VBA Demo: Radius, m Volume, m^3 Surface Area, m^2 5.00 6.00 7.00 After program execution: Excel VBA Demo: Radius, m Volume, m^3 Surface Area, m^2 5.00 523.60 314.16 6.00 904.78 452.39 7.00 615.75

Similar presentations

OK

Introduction to Excel 20021 Formulas, Functions and References.

Introduction to Excel 20021 Formulas, Functions and References.

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on carbon and its compounds notes Ppt on solar system download Stem and leaf display ppt online Ppt on mindset change Ppt on p block elements chemistry class 11 Ppt on rivers of india in hindi Free download ppt on brain machine interface Ppt on series and parallel circuits physics Hrm ppt on recruitment strategies Ppt on nanotechnology in mechanical engineering