View Single Post
  #11   Report Post  
Posted to microsoft.public.excel.programming
MichaelDavid MichaelDavid is offline
external usenet poster
 
Posts: 100
Default For Each Next Loop behaving in unexpected manner

Hi Jacob:
Thank you very much for your kind help. I tried your solution and it
works, but it seems to run in about the same time as the one I devised,
because doing the Goto Sheets(intSheet).Range("G" & lngRow + 9) command
essentially selects the sheets in succession, and, in each case, goes to cell
("G" & lngRow + 9) on that sheet, thus leaving that cell selected. Please
let me know of the advantages of your solution over mine. If the advantages
strike me as significant (such as less error prone, actually faster, lesser
drain on resources, etc.), I will definitely use your solution rather than
mine. But I was really hoping that there might be a way of having the cell
selected on each sheet without actually selecting or going to that sheet
which really slows things down.

--
May you have a most blessed day!

Sincerely,

Michael Fitzpatrick


"Jacob Skaria" wrote:

Try the below..

Sub Macro()
Dim ws As Worksheet, lngRow As Long
For intSheet = 1 To Sheets.Count - 1
lngRow = Sheets(intSheet).Cells(Rows.Count, "W").End(xlUp).Row
Application.Goto Sheets(intSheet).Range("G" & lngRow + 9)
Next
Sheets(1).Activate
End Sub


--
Jacob


"MichaelDavid" wrote:

Hi Tom:
I played around with the code for a few hours, and here is what I came up
with:

Dim WS As Worksheet
For Each WS In ActiveWorkbook.Worksheets
If WS.Name < "Sheet1" Then
LstRowData = WS.Range("O2")
WS.Activate
WS.Cells(LstRowData + 9, "W").Select
End If
Next WS

which is very similar to what you came up with.

Apparently the WS.Activate instruction is absolutely necessary. Excel does
not allow
a cell to be selected unless the worksheet it is on has been activated.
Perhaps you can come up with a way to omit WS.Activate instruction. Just
removing the WS.Activate instruction results in the error message: "Run-time
error '1004': Select method of Range class failed." Thanks for all your kind
help.

--
May you have a most blessed day!

Sincerely,

Michael Fitzpatrick


"tompl" wrote:

I think I get it now. First you have to select the worksheet, then you can
select the cell.

Try this:

For Each WS In ActiveWorkbook.Worksheets
If WS.Name < "Sheet1" Then
LstRowData = Range("O2") 'if LstRowData was computed elsewhere why is
'this here? should it be WS.Range("O2") = LstRowData? I think this line
'might need to be eliminated here. Or identify what sheet Range("O2") is on.
WS.select
Cells(LstRowData + 9, "W").Select
End If
Next