if..then..else error vba

winde

New Member
Joined
Nov 27, 2018
Messages
32
Hi

Anyone able to help me debug my code below? it kept prompting me compile error: else without if

where did i make a mistake?


Dim s As String
Dim r As Long
Dim c As Long


'set active sheet
Set ws = ActiveSheet


'finds the last row
lstrow = ws.UsedRange.Rows.Count


c = 2


For r = 1 To lstrow

If Cells(r, c) = "" Then Cells(r, c) = Cells(r, c - 1)
Else
Cells(r, c) = Cells(r - 1, c)
End If


Next r


End Sub
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Try
Code:
Dim s As String
Dim r, lstrow As Long
Dim c As Long
Dim ws As Worksheet


'set active sheet
Set ws = ActiveSheet
'finds the last row
lstrow = ws.UsedRange.Rows.Count


c = 2


For r = 1 To lstrow


If Cells(r, c) = "" Then
Cells(r, c) = Cells(r, c - 1)
Else
Cells(r, c) = Cells(r - 1, c)
End If


Next r
 
Upvote 0
Try
Code:
Dim s As String
Dim r, lstrow As Long
Dim c As Long
Dim ws As Worksheet


'set active sheet
Set ws = ActiveSheet


'finds the last row
lstrow = ws.UsedRange.Rows.Count


c = 2


For r = 1 To lstrow


If Cells(r, c) = "" Then
Cells(r, c) = Cells(r, c - 1)
Else
Cells(r, c) = Cells(r - 1, c)
End If


Next r
 
Upvote 0
This if:

Code:
If Cells(r, c) = "" Then Cells(r, c) = Cells(r, c - 1)

placed on one line doesnt require an end if. So as you have false conditions too you need:

Code:
If Cells(r, c) = "" Then 
Cells(r, c) = Cells(r, c - 1)
Else
Cells(r, c) = Cells(r - 1, c)
End If
 
Upvote 0
Also, make sure you declare ALL variables
Code:
dim ws as worksheet, lstrow as long
Set ws = ActiveSheet
lstrow = ws.UsedRange.Rows.Count
 
Upvote 0

Forum statistics

Threads
1,213,544
Messages
6,114,239
Members
448,555
Latest member
RobertJones1986

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top