help me understand why this bit of code works one way but not the other... (?)

kbishop94

Active Member
Joined
Dec 5, 2016
Messages
476
Office Version
  1. 365
Platform
  1. Windows
  2. MacOS
This is ok:

Code:
Dim lCol As Long
    lCol = ActiveSheet.UsedRange.Columns.Count


    For Each Cell In Range(Cells(4, 6), Cells(4, lCol)).SpecialCells(xlCellTypeVisible)


If Cell = "E" Then Call Macro2 Else CommandButton28.BackColor = &H8000000F


Next


End Sub

But this is not, even though I've seen code scripted in this manner before and it works(?) (everything is the same, its just not on 1 line like the first code... it even "corrects me" by automatically changing the "Else CommandButton28" to "Else: CommandButton28... :confused:) It "accepts" the code when I type it in and enter it... but when its executed I get "Compile error: Next without For" (even though its the same thing as the first code I posted and I do not get the "next without for" when its ran.)

Code:
Dim lCol As Long


    lCol = ActiveSheet.UsedRange.Columns.Count
    
    For Each Cell In Range(Cells(4, 6), Cells(4, lCol)).SpecialCells(xlCellTypeVisible)


If Cell = "E" Then


Call Macro2


Else: CommandButton28.BackColor = &H8000000F


Next


End Sub

I dont care if I've made myself look like complete idiot by asking this... I really want to understand and learn VBA.

THanks
 

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
I think with VBA functionality, IF statements on a single like dont need "end if"

In your 2nd code, its multi line so End If is needed before Next
 
Upvote 0

Forum statistics

Threads
1,223,898
Messages
6,175,274
Members
452,628
Latest member
dd2

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