user2786962
user2786962

Reputation: 469

If else statement in VBA

I am writing the following code in vba:

If row_count = 28 Then Range("A28").Select
    Else
    Range("A29").Select
    Selection.End(xlDown).Select
    Range("B" & row_count & ":AE" & row_count).Select
    Range(Selection, Selection.End(xlUp)).Select
    Application.CutCopyMode = False
    Selection.FillDown
    End If

It's giving me an error that else without if.

How can i correct the code?

Upvotes: 0

Views: 173

Answers (1)

paxdiablo
paxdiablo

Reputation: 881113

Move the Range("A28").Select on to its own line (not as part of the if line), thus:

If row_count = 28 Then
    Range("A28").Select
Else
    Range("A29").Select
    Selection.End(xlDown).Select
    Range("B" & row_count & ":AE" & row_count).Select
    Range(Selection, Selection.End(xlUp)).Select
    Application.CutCopyMode = False
    Selection.FillDown
End If

There are two forms of the if construct, the single line and multi-line. If you put the statements for the then condition on the same line, it's considered a single line variant so the else has to also be on the same line.

Because, in your case, it's not on the same line, VB is assuming the single line is an if statement with no else clause, so the "naked" else on the next line is invalid.

Upvotes: 3

Related Questions