Problem

You need to loop through some code and don't know the VBA syntax for loops.

Solution

Use a `For` loop like the one shown in Example 2-12.

Example 2-12. For loop

For i = 1 To n ' Statements go here Next i |

`For` loops are sometimes called `For Next` loops because you use the `Next` statement to bound the code over which you want to loop. Also, the `Next` statement increments the counter variable, `i` in this case, by 1 each time through the loop. In this example, the loop starts with the counter equal to 1 and ends when the counter equals the value stored in the variable `n`. You can hardcode start and end values or use variables.

Discussion

To increment the counter in a `For` loop by a something other than 1, use the `Step` keyword as shown in Example 2-13.

Example 2-13. For loop

For i = 1 To n Step 2 ' Statements go here Next i |

In this case, the counter variable gets incremented by 2 each time through the loop. You may also use a negative step value to count down from a start value to an end value.

Sometimes it's necessary to exit a `For` loop before the counter actually reaches the end value. To exit a `For` loop, use the `Exit For` statement. You can put this in a conditional statement to exit only under specific conditions, as shown in Example 2-14.

Example 2-14. Exit For statement

For i = 1 To n ' Statements go here ' Test an exit condition If time > 32000 Then Exit For End If ' May have more statements here Next i |

When an `Exit For` statement is encountered, code execution will jump from the `Exit For` statement to the first statement after the `Next` statement of the loop.

For most of the calculations discussed in this book that require looping, plain old `For` loops will work just fine. In fact, I use `For` loops probably 90% of the time, but in some special cases `Do` loops are a better choice.

`Do` loops are useful when you're not actually iterating a counter but are testing some condition (a logical statement) instead. In VBA there are actually four different ways of writing `Do` loops, as shown in Example 2-15.

Example 2-15. Four different Do loops

Do While (dtime < 32000) ' Statements go here Loop Do ' Statements go here Loop While (dtime < 32000) Do Until (dtime > 32000) ' Statements go here Loop Do ' Statments go here Loop Until (dtime > 32000) |

The first two loops in Example 2-15 are `Do While` loops, and the last two are `Do Until` loops.

`Do While` loops execute the loop as long as the condition following the `While` keyword is `TRue`. In this example, the condition is enclosed in parentheses. Note the difference between the two `Do While` loops. In the first case the condition is tested before the code in the loop is executed, while in the second case the code in the loop is executed once before the condition is tested. This means that in the first case it's possible the code within the loop may not get executed, while in the second case the code within the loop will get executed at least once.

`Do Until` loops execute the loop as long as the condition following the `Until` keyword is `false` (that is, until the condition becomes `true`). As with `Do While` loops, there are two ways to write `Do Until` loops. In the first case shown in Example 2-15 the condition is tested before the code within the loop is executed, while in the second case the code in the loop is executed before the condition is tested.

As with `For` loops, you can exit a `Do` loop anytime before the looping condition is satisfied, using an `Exit Do` statement.

See Also

VBA also has a `For Each` loop that is used to loop over collections of objects. These loops are useful when interfacing with Excel objects, such as cells. For example, you can use a `For Each` construct to loop over a range of selected cells in a spreadsheet without actually knowing the number of cells in the range. See the help topic "Using For Each...Next Statements" in the VBA help for more information on these loops. Press F1 in the VBA IDE to access the VBA help guide.

Using Excel

- Introduction
- Navigating the Interface
- Entering Data
- Setting Cell Data Types
- Selecting More Than a Single Cell
- Entering Formulas
- Exploring the R1C1 Cell Reference Style
- Referring to More Than a Single Cell
- Understanding Operator Precedence
- Using Exponents in Formulas
- Exploring Functions
- Formatting Your Spreadsheets
- Defining Custom Format Styles
- Leveraging Copy, Cut, Paste, and Paste Special
- Using Cell Names (Like Programming Variables)
- Validating Data
- Taking Advantage of Macros
- Adding Comments and Equation Notes
- Getting Help

Getting Acquainted with Visual Basic for Applications

- Introduction
- Navigating the VBA Editor
- Writing Functions and Subroutines
- Working with Data Types
- Defining Variables
- Defining Constants
- Using Arrays
- Commenting Code
- Spanning Long Statements over Multiple Lines
- Using Conditional Statements
- Using Loops
- Debugging VBA Code
- Exploring VBAs Built-in Functions
- Exploring Excel Objects
- Creating Your Own Objects in VBA
- VBA Help

Collecting and Cleaning Up Data

- Introduction
- Importing Data from Text Files
- Importing Data from Delimited Text Files
- Importing Data Using Drag-and-Drop
- Importing Data from Access Databases
- Importing Data from Web Pages
- Parsing Data
- Removing Weird Characters from Imported Text
- Converting Units
- Sorting Data
- Filtering Data
- Looking Up Values in Tables
- Retrieving Data from XML Files

Charting

- Introduction
- Creating Simple Charts
- Exploring Chart Styles
- Formatting Charts
- Customizing Chart Axes
- Setting Log or Semilog Scales
- Using Multiple Axes
- Changing the Type of an Existing Chart
- Combining Chart Types
- Building 3D Surface Plots
- Preparing Contour Plots
- Annotating Charts
- Saving Custom Chart Types
- Copying Charts to Word
- Recipe 4-14. Displaying Error Bars

Statistical Analysis

- Introduction
- Computing Summary Statistics
- Plotting Frequency Distributions
- Calculating Confidence Intervals
- Correlating Data
- Ranking and Percentiles
- Performing Statistical Tests
- Conducting ANOVA
- Generating Random Numbers
- Sampling Data

Time Series Analysis

- Introduction
- Plotting Time Series Data
- Adding Trendlines
- Computing Moving Averages
- Smoothing Data Using Weighted Averages
- Centering Data
- Detrending a Time Series
- Estimating Seasonal Indices
- Deseasonalization of a Time Series
- Forecasting
- Applying Discrete Fourier Transforms

Mathematical Functions

- Introduction
- Using Summation Functions
- Delving into Division
- Mastering Multiplication
- Exploring Exponential and Logarithmic Functions
- Using Trigonometry Functions
- Seeing Signs
- Getting to the Root of Things
- Rounding and Truncating Numbers
- Converting Between Number Systems
- Manipulating Matrices
- Building Support for Vectors
- Using Spreadsheet Functions in VBA Code
- Dealing with Complex Numbers

Curve Fitting and Regression

- Introduction
- Performing Linear Curve Fitting Using Excel Charts
- Constructing Your Own Linear Fit Using Spreadsheet Functions
- Using a Single Spreadsheet Function for Linear Curve Fitting
- Performing Multiple Linear Regression
- Generating Nonlinear Curve Fits Using Excel Charts
- Fitting Nonlinear Curves Using Solver
- Assessing Goodness of Fit
- Computing Confidence Intervals

Solving Equations

- Introduction
- Finding Roots Graphically
- Solving Nonlinear Equations Iteratively
- Automating Tedious Problems with VBA
- Solving Linear Systems
- Tackling Nonlinear Systems of Equations
- Using Classical Methods for Solving Equations

Numerical Integration and Differentiation

- Introduction
- Integrating a Definite Integral
- Implementing the Trapezoidal Rule in VBA
- Computing the Center of an Area Using Numerical Integration
- Calculating the Second Moment of an Area
- Dealing with Double Integrals
- Numerical Differentiation

Solving Ordinary Differential Equations

- Introduction
- Solving First-Order Initial Value Problems
- Applying the Runge-Kutta Method to Second-Order Initial Value Problems
- Tackling Coupled Equations
- Shooting Boundary Value Problems

Solving Partial Differential Equations

- Introduction
- Leveraging Excel to Directly Solve Finite Difference Equations
- Recruiting Solver to Iteratively Solve Finite Difference Equations
- Solving Initial Value Problems
- Using Excel to Help Solve Problems Formulated Using the Finite Element Method

Performing Optimization Analyses in Excel

- Introduction
- Using Excel for Traditional Linear Programming
- Exploring Resource Allocation Optimization Problems
- Getting More Realistic Results with Integer Constraints
- Tackling Troublesome Problems
- Optimizing Engineering Design Problems
- Understanding Solver Reports
- Programming a Genetic Algorithm for Optimization

Introduction to Financial Calculations

- Introduction
- Computing Present Value
- Calculating Future Value
- Figuring Out Required Rate of Return
- Doubling Your Money
- Determining Monthly Payments
- Considering Cash Flow Alternatives
- Achieving a Certain Future Value
- Assessing Net Present Worth
- Estimating Rate of Return
- Solving Inverse Problems
- Figuring a Break-Even Point

Index

Excel Scientific and Engineering Cookbook (Cookbooks (OReilly))

ISBN: 0596008791

EAN: 2147483647

EAN: 2147483647

Year: N/A

Pages: 206

Pages: 206

Authors: David M Bourg

Similar book on Amazon

Flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net