ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   For Next Question (https://www.excelbanter.com/excel-programming/339790-next-question.html)

Fredg

For Next Question
 

I have a workbook that I use several For Next loops in. I was wonderin
if someone could explain the issues with using or not using th
vairable after the Next.

For example I have:

Count = 0
For Each cell In Selection
Count = Count + 1
cell.Value = "D" & Count
Next

If I put "Cell" after Next it works the same way.

Count = 0
For Each cell In Selection
Count = Count + 1
cell.Value = "D" & Count
Next cell

Which is the best programming style? I would think adding the variabl
name after the Next would be correct.

Thanks
Fre

--
Fred
-----------------------------------------------------------------------
Fredg's Profile: http://www.excelforum.com/member.php...fo&userid=2632
View this thread: http://www.excelforum.com/showthread.php?threadid=46675


Fredg

For Next Question
 

Also, of the two blocks of codes which would be the most correct, bot
work the same way. I would think the second one, but I can not explai
WHY it would be better.

-----
Sub countsheets()

For Each Worksheet In ActiveWorkbook.Worksheets
MsgBox Worksheet.Name
Next

End Sub

-----

Sub countsheets()

Dim Item as WorkSheet
For Each Item In ActiveWorkbook.Worksheets
MsgBox Item.Name
Next Item

End Su

--
Fred
-----------------------------------------------------------------------
Fredg's Profile: http://www.excelforum.com/member.php...fo&userid=2632
View this thread: http://www.excelforum.com/showthread.php?threadid=46675


Tom Ogilvy

For Next Question
 
Putting the loop variable after the next makes it easier to see where the
loop begins and ends.

Using worksheet as a variable probably isn't the best of ideas. Declaring
your variable is good, so teh second is probably perferred.

--
Regards,
Tom Ogilvy

"Fredg" wrote in
message ...

Also, of the two blocks of codes which would be the most correct, both
work the same way. I would think the second one, but I can not explain
WHY it would be better.

-----
Sub countsheets()

For Each Worksheet In ActiveWorkbook.Worksheets
MsgBox Worksheet.Name
Next

End Sub

-----

Sub countsheets()

Dim Item as WorkSheet
For Each Item In ActiveWorkbook.Worksheets
MsgBox Item.Name
Next Item

End Sub


--
Fredg
------------------------------------------------------------------------
Fredg's Profile:

http://www.excelforum.com/member.php...o&userid=26328
View this thread: http://www.excelforum.com/showthread...hreadid=466757





All times are GMT +1. The time now is 11:24 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com