Solved

Case statements in Excel 2010?

Posted on 2012-08-15
1,739 Views
Is it possible to use the equivalent of a case statement in Excel 2010? By that I mean can an Excel command be used to produce different results based on the data contents of the cell. Some database products can do case one, case two, case three, etc. and by the software picking the correct case, giving you a different answer or calculation for each case.
0
Question by:mzimerman

LVL 92

Assisted Solution

To an extent, yes.

For example, you can use IF() to do this:

=IF(<logical test>,<expression if true>,<expression if false)

You can also embed IF() expressions:

=IF(A1="yes",1,IF(A1="no",2,IF(A1="maybe",3,4)))

If the possible values you need to test are always 1,2,3,...,N then you can use CHOOSE():

=CHOOSE(A1,"one","two","three","four")

In VBA, the function that comes closest is probably Switch(), but that is unavailable in Excel unless you create a UDF wrapper for it.
0

Assisted Solution

Via code or formula?  If by formula, you can certainly use nested "IF" statements to do the job.  Via code - Select Case will do the trick.  I can provide examples once you clarify what you're attempting to do.
0

LVL 92

Assisted Solution

0

LVL 4

Assisted Solution

There's no SWITCH command per se, that I am aware of, but the functionality can be replicated using IF statements and, depending on the scenario, some other options such as LOOKUP, MATCH, etc.

Do you have a specific example you can explain or post?
0

LVL 92

Assisted Solution

Note that for my suggestions above I was assuming you are trying to do this in Excel formulas.  In VBA, as SmittyNet indicates, you have the If...ElseIf...Else and Select Case control structures.
0

LVL 44

Accepted Solution

As a macro which can be use as a user defined formula. eg =MyMacro()

``````Function MyMacro()

Select Case Range("A1").Value
Case 1
' Do something
Case < 8
' Do something else
Case Else
' Do default processing
End Select

End Function
``````
0

LVL 44

Expert Comment

Is there anything more we can do for you here?
0

Featured Post

Improved? Move/Copy Add-in Replacement - How to avoid the annoying, “A formula or sheet you want to move or copy contains the name XXX, which already exists on the destination worksheet.” David Miller (dlmille)  It was one of those days… I wa…
How to quickly and accurately populate Word documents with Excel data, charts and images (including Automated Bookmark generation) David Miller (dlmille) Synopsis In this article you’ll learn how to use ExcelToWord! to copy data,charts, shapes …
Viewers will learn the basics of slicers and timelines for both PivotTables and standard Excel tables in Excel 2013.