View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
K Dales[_2_] K Dales[_2_] is offline
external usenet poster
 
Posts: 1,163
Default If Then Else with Exit For

To perhaps explain the confusion:
There are two forms of an If... Then statement; a one-line statement and a
multiline statement.

The one line statement looks like this:
If condition Then statement1 [Else statement2]
The Else part is optional but if included must be on the same line; I often
use the line continuation character "_" to separate it just so I can read it
more easily, but it still counts as a single line.

The multiple line statement looks like:
If condition1 Then
statement1a
statement1b
statement1c...
[Else
statement2a
statement2b
statement2c...]
End If
Again, the Else part is optional. But what will not work is to combine the
two, as in this (error) example:
If condition1 Then statement1
Else
statement2a
statement 2b
End If

If you look at your original code, this was the error.

If blnTest = True Then Exit For ' SINGLE LINE format
Else ' MULTIPLE LINE format
If IsNumeric(c) Then c.EntireColumn.Hidden
blnTest = True
End If

'Else without If' means it found an Else alone on a line where it is not
expected (because the If ... Then above is complete; it is not part of a
multiline If statement)

For the next one:
If blnTest = True Then Exit For ' SINGLE LINE - this is OK here
If IsNumeric(c) Then c.EntireColumn.Visible = False 'SINGLE LINE
format again
blnTest = True
End If ' End If cannot be used here, since the IF was ended
already

'End If without block If' comes when the debugger hits an End If that does
not have a multiline If statement, i.e. a 'block If', above it.

Correct form (the other replies are also valid, but this is the way to write
a technically correct If... Then...Else to deal with these types of
conditions):

If blnTest = True Then
Exit For
Else
If IsNumeric(c) Then
c.EntireColumn.Hidden
blnTest = True
End If
End If

--
- K Dales


"Brassman" wrote:


Try fixing one more thing...

Code:
--------------------

Option Explicit

Sub TestValue()
Dim c As Range
Dim blnTest As Boolean

blnTest = False

For Each c In Range("C:C")
If blnTest = True Then Exit For
If IsNumeric(c) Then
c.EntireColumn.Visible = False
blnTest = True
End If
Next c
End Sub

--------------------

keep "c.EntireColumn.Visible (or Hidden)" on a separate line than "If
IsNumeric(c) Then"


--
Brassman
------------------------------------------------------------------------
Brassman's Profile: http://www.excelforum.com/member.php...o&userid=13290
View this thread: http://www.excelforum.com/showthread...hreadid=494489