Loop Through worksheets

  • Thread starter Thread starter Stephen
  • Start date Start date
S

Stephen

Hi All,

I need a VBA code for looping through all the worksheets and add th
=today() is cell A1, except in sheet "Overview".

Please help:)

Stephe
 
Dim sh as Worksheet
for each sh in Activeworkbook.Worksheets
if lcase(sh.name) <> "overview" then
sh.range("A1").Formula = "=Today()"
' or for a hard coded date
' sh.Range("A1").Value = Date
sh.range("A1").NumberFormat = "mm/dd/yyyy"
end if
Next
 
Stephen, give this a try.

Troy

Sub AddToday()
Dim ii As Integer

For ii = 1 To Worksheets.Count
If Worksheets(ii).Name <> "Overview" Then
Worksheets(ii).Range("A1").Formula = "=today()"
End If
Next ii
End Sub
 
Thank you all. The code works great!!

Stephen
*Stephen, give this a try.

Troy

Sub AddToday()
Dim ii As Integer

For ii = 1 To Worksheets.Count
If Worksheets(ii).Name <> "Overview" Then
Worksheets(ii).Range("A1").Formula = "=today()"
End If
Next ii
End Sub
 
The 2 replies to the original question brings up a couple of points
about VBA programming I do not understand, hope someone can enlighten
me.
1. Why dim a variable (in this case "sh") to replace Worksheets? Why not
just work directly with the built in value as the second response does?
2. Once having "Dim sh as Worksheet" why is it that the statement "for
each sh in Activeworkbook.Worksheets" automatically assigns sh all of
the worksheets since sh has been defined as only a (one) worksheet?
Thanks
 
Hi
both ways are possible but Tom's solution using a
worksheet object has the following benefits (IMHO)
- easier to write using an object reference
- you could use this reference to store the old object and
use it later in your code

Also using a for ... each construct is possible. This
statement will loop through all worksheets in the
collection 'worksheets' and assigns the current loop value
to this object variable
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top