Programming Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
 
User Name:
Password:
Remember me
Iron Speed
Go Back   ASP Free ForumsOtherProgramming Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread ASP Free Forums Sponsor:
Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!
  #1  
Old April 10th, 2008, 10:17 PM
don94403's Avatar
don94403 don94403 is offline
Contributing User
ASP Free Beginner (1000 - 1499 posts)
 
Join Date: Jan 2007
Location: Northern California
Posts: 1,171 don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level)don94403 User rank is Captain (20000 - 30000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 32 m 3 sec
Reputation Power: 251
Tutorial: Conditionals - If-then-else, Immediate If, Select Case

A hundred years ago, when I studied programming, my instructor taught us that all of programming could be summed up by four kinds of operations:

- Assignment: assigning a value to a variable;
- Branching: determining the flow of the logic based on a conditional test;
- Looping: repeating the same block of steps until some defined stopping condition;
- Formatting: manipulating strings, numbers (Math) and dates.

That's still basically true, although it has been much more finely divided, with the introduction of object oriented programming, etc.

In this tutorial, I will try to address CONDITIONALS in Microsoft Visual Basic for Applications (VBA).

VBA has several alternative syntaxes for conditionals. They are largely interchangeable; that is, you can usually accomplish the same result in more than one way, but often one method will be simpler than others.

The most well known conditional is the IF-THEN-ELSE syntax. In its simplest form it is:
VBA Code:
Original - VBA Code
    If [a condition that evaluates either True or False] Then     [take one action] Else     [take a different action] Endif
The Else block is optional.

If-Then statements can be nested:
VBA Code:
Original - VBA Code
    If [condition] Then     [take action 1] Else     If [another condition] Then         [take action 2]     Else         [take action 3]     Endif Endif
And so forth. Even beginning programmers should understand If-Then-Else structures.

As you can see, if you have more complex logic and required actions, this nesting could become rather complex, although, in theory, any logic could be represented in this way.

A short form syntax available in VBA is the "IMMEDIATE IF" function. In a single line of VBA code, you can assign a value based on several conditions. For example, to set the value of a commission rate variable, depending on the PositionLevel of the salesperson, you might do the following:
VBA Code:
Original - VBA Code
    Dim PosLevel As Integer Dim CommRate As Double CommRate = Iif (PosLevel = 1, .15, .2)

This results in the CommRate being set to .15 if the PosLevel equals 1, otherwise it is set to .20. The syntax is:

Iif( [condition - true or false], [value if true], [value if false] )

This can be expanded:

CommRate = Iif (PosLevel = 1, .15, Iif (PosLevel = 2, .2, Iif(PosLevel = 3, .25), 0)))

So if PosLevel=1 is true, CommRate will be .15; if not, and PosLevel=2, CommRate will be .2; if not, and PosLevel=3, CommRate will be .25; if not either 1, 2 or 3, CommRate will be 0.

Note the way the parentheses are positioned; beginners often have trouble with them in Immediate If statements. A quick check is to make sure you have the same number of opening and closing parentheses.

Immediate If is a compact syntax for assigning a value to a variable, but it can become hard to read if there are more than just a few valid choices, and it can only assign a value, it cannot execute a block of code, as If-Then-Else can.

Finally, VBA has a SELECT CASE structure, whereby the value of a single variable can be tested and the code to be executed for each condition can be determined, based on that value. The syntax is:
VBA Code:
Original - VBA Code
    Select Case [variable]     Case: [value1]         [code block]         ...         ...     Case: [value2]         [code block]         ...     Case: [value3]         [code block]         ...     Case Else:         [code block]         ... End Select
That means that the variable named in the first line will be tested against the values in each succeeding Case: statement until the comparison is true, then the code in that block will be executed and it will skip over the other Case: statements, to the End Select. The Case Else: statement is optional.

An example would be a function written to determine the appropriate commission rate for a salesperson with a Job Category and a Monthly Sales amount. Let's say that commissions are based on this table:

Code:
Monthly Sales      Jr. Salesperson   Sr. Salesperson   Dept. Manager
   Under 5,000            5%                8%               10%
   5,001 - 10,000         8%               10%               12%
  10,001 - 15,000        10%               12%               14%
   Over 15,000           12%               14%               16%

You would want to calculate the appropriate commission amount by calling a function "GetRate()" with two arguments, like this:

Commission = GetRate(MoSales, JobCat) * MoSales

The function would look like this:
VBA Code:
Original - VBA Code
    Public Function GetRate (MoSales As Double, JobCat As Integer) As Double     Select Case MoSales         Case Is <= 5000:             GetRate = Iif(JobCat=1, .05, Iif(JobCat=2, .08, Iif(JobCat=3, .1, 0)))         Case Is <= 10000:             GetRate = Iif(JobCat=1, .08, Iif(JobCat=2, .1, Iif(JobCat=3, .12, 0)))         Case Is <= 5000:             GetRate = Iif(JobCat=1, .1, Iif(JobCat=2, .12, Iif(JobCat=3, .14, 0)))         Case Else:             GetRate = Iif(JobCat=1, .12, Iif(JobCat=2, .14, Iif(JobCat=3, .16, 0)))     End Select End Function
This a very compact and understandable syntax, and fairly easy to read. It also returns zero commission if the JobCat is omitted or is invalid. Do you see why?

So this is an example of using two different conditional syntaxes together, to do a simple lookup. If the number of choices was high, it might be better to code this into a table, but for just 4 ranges of monthly sales and 3 job categories, it would be much simpler than setting up a table, and much faster in execution, since it doesn't have to access the table on the hard drive. It would, however, require editing the VBA code if the commission basis changed, so that would need to be taken into account as a factor in deciding how to code it.
__________________
Experience is the thing you have left when everything else is gone.

Last edited by don94403 : April 11th, 2008 at 04:56 AM.

Reply With Quote
Reply

Viewing: ASP Free ForumsOtherProgramming Help > Tutorial: Conditionals - If-then-else, Immediate If, Select Case


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

 Free IT White Papers!
 
Accelerating Trading Partner Performance
One in five. That's how many partner transactions have at least one error. That is an amazing statistic, particularly given the extraordinary leaps in innovation across the global supply chain during the past two decades. Download this white paper to learn more.

 
Competing on Analytics
This Tech Analysis is designed to help identify characteristics shared by analytics competitors, and includes information about 32 organizations that have made a commitment to quantitative, fact-based analysis.

 
Cost Effective Scaling with Virtualization and Coyote Point Systems
An overview of the industry trend toward virtualization, how server consolidation has increased the importance of application uptime and the steps being taken to integrate load balancing technology with virtualized servers.

 
Five Checkpoints to Implementing IP Telephony
Implementation planning for IP PBX software and IP telephony has become vital as businesses replace discontinued legacy PBX phone systems. This informative whitepaper outlines five "checkpoints" for any implementation plan that will help make IP communications a successful proposition.

 
Hosted Email Security: Staying Ahead of New Threats
In the last two years, email has become a fierce battleground between the nefarious forces of spam and malware, and the heroes of messaging protection. The spam volumes increased alarmingly every month, bringing clever new forms of phishing and virus propagation attacks.

 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway