Select Last visible Sheet

Dannyh1

Well-known Member
Joined
Nov 18, 2009
Messages
1,144
Hi

I have code to select last sheet of a workbook

Code:
 Sheets(Sheets.Count).Select

This code will error if sheets a hidden.

Could someone please advise how to adapt this to select last visible sheet in workbook?

Many Thanks
 

Excel Facts

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.

schielrn

Well-known Member
Joined
Apr 4, 2007
Messages
6,941
This is one way:

Code:
for i = sheets.count to 1 step -1
if sheets(i).visible = -1 then
     sheets(i).select
     exit sub
end if
next i
Hope that helps and this is untested.
 

Dannyh1

Well-known Member
Joined
Nov 18, 2009
Messages
1,144
Thanks schielrn

I think I am positioning this incorrectly in my code though

This is what I have:

Code:
 Dim rng As Range
 Set rng = Sheets("Files").Range("A1:A61")
 
 For Each cl In rng
 
 Workbooks.Open Filename:=cl.Value
 
    For i = Sheets.Count To 1 Step -1
    If Sheets(i).Visible = True Then
     Sheets(i).Select
     Exit Sub
    End If
    Next i
 Range("U1").Select
 ActiveCell.FormulaR1C1 = _
        "=MID(CELL(""filename"",RC[-20]),FIND(""]"",CELL(""filename"",RC[-20]))+1,256)"
 
 ActiveWorkbook.Save
 ActiveWorkbook.Close
 
 Next cl

When I run this, it stops before ActiveWorkbook.Save (i.e. only does it for one file)

Can you see where I have gone wrong with my code?

Thanks again
 

schielrn

Well-known Member
Joined
Apr 4, 2007
Messages
6,941
Maybe where I have Exit Sub change to Exit For. This way it doesn't exit out of your routine.

Hope that helps.
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,164,628
Messages
5,838,452
Members
430,549
Latest member
jayjay2022

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
Top