Loop to hide sheets - vba

Currently, I am using this VBA code to hide all sheets in my spreadsheet:
Sub HideSheets()
Sheet1.Visible = False
Sheet2.Visible = False
Sheet3.Visible = False
Sheet4.Visible = True
End Sub
This code runs perfectly.
However, since I have more than just 4 sheets in my original file I would like to have a solution with a loop. Therefore, I tried to go with the following formula:
Sub LoopHideSheets()
Dim b As Worksheet
For Each b In Worksheets
b.Select
ActiveWindow.Visible = False
Next b
End Sub
Once I run this code my Excel file crashes. I guess the reason for this is that at least one file needs to stay visible. Do you know what I have to change my loop code so all sheets getting hidden instead of Sheet4?

Sub LoopHideSheets()
Dim b As Worksheet
For Each b In Worksheets
If b.Name <> "DontHide" Then 'whatever the sheet name is to not hide
b.Visible = False
End If
Next b
End Sub

This will hide every sheet that is not named "Sheet4" - but be careful, you need to ensure Sheet4 exists or you will get an error.
Sub LoopHideSheets()
Dim b As Worksheet
For Each b In Worksheets
If b.Name <> "Sheet4" Then b.Visible = False
Next b
End Sub
You might want to hide all sheets other than the one currently active..?
If b.Name <> ActiveSheet.Name Then b.Visible = False
However, you may need to hide all but 1 (hey, I've no idea why) as per other answers. To do this properly, you need to count visible sheets and only deal with those:
Sub LoopHideSheets()
Dim b As Worksheet, shtcnt As Long
'Count up all visible sheets
For Each b In Worksheets
If b.Visible = True Then shtcnt = shtcnt + 1
Next b
'Hide each visible sheet until only 1 is left
For Each b In Worksheets
If b.Visible = True And shtcnt > 1 Then
shtcnt = shtcnt - 1
b.Visible = False
End If
Next b
End Sub

Alternatively you can catch the error with error handling
Sub HideAllSheets()
Dim b As Worksheet
For Each b In Worksheets
On Error Resume Next 'disable error reporting
b.Visible = False
If Err.Number = 1004 Then
MsgBox "The last sheet must stay visible" 'remove if you don't want a message
Exit Sub
End If
On Error GoTo 0 're-enable error handling. Don't forget this line!
Next b
End Sub

If You always want to have last sheet visible you could use this
Sub HideSheets()
Dim i As Long
With ThisWorkbook
For i = 1 To .Sheets.Count - 1
.Sheets(i).Visible = False
Next i
End With
End Sub

Related

Want to write formula in cell if x=y, otherwise blank cell, using VBA

Let me better explain. If the value of A1 is "0" then in A2 I want the formula =vlookup(B1,C1:E3,2,0), If the value of A1 is "1", then I simply want a blank cell value for A2. I want this macro to occur upon opening the excel. I thought this would work but it is not
Sub test()
Dim indicator As Value
Dim result As String
indicator = Range("A1").Value
If indicator = 0 Then result = "=VLOOKUP(A3,C1:D3,2,0)"
Range("a2").Value = result
End Sub
in the ThisWorkbook section put this in
Sub Workbook_open()
If Range("A1") = 0 Then
Range("A2").Formula = "=vlookup(B1,C1:E3,2,0)"
ElseIf Range("A1") = 1 Then
Range("A2").ClearContents
Else
End If
End Sub
If you want the code to run on a specific sheet, not the one that happened to be active when the file was last saved, then try this instead:
Sub Workbook_open()
Dim ws As Worksheet
' define the worksheet to be changed here:
Set ws = ThisWorkbook.Worksheets("Sheet5")
If ws.Range("A1") = 0 Then
ws.Range("A2").Formula = "=vlookup(B1,C1:E3,2,0)"
ElseIf Range("A1") = 1 Then
ws.Range("A2").ClearContents
Else
End If
End Sub

Populate ComboBox With Sheet Names Dynamically

I am having trouble with populating a combo box on a excel ribbon dynamically.
I wish for the combo box to be populated using the names of the sheets of the workbook dynamically.
I am able to select the sheet names already presentin the combo box that is placed on the ribbon however I do not seam to be able to code the VBA to populate the combo box with the sheet names if I add them or modify the name.
I have written below code but its not working :
Sub SelectionFeuille_GetItemLabel(control As IRibbonControl, index As Integer, ByRef returnedVal)
Dim dTime As Date
dTime = Now + TimeValue("00:00:01") 'hh:mm:ss
Application.OnTime dTime, "Refresh_all"
returnedVal = ActiveWorkbook.Worksheets(index + 1).Name
End Sub
Please help me....
The simplest way I've found to do this is to capture the Calculate event, and I do that by having a hidden worksheet with formulae to each sheet in its cells. It's far from perfect and, if truth be told, is a pretty ugly workaround, but at least it's food for thought for you. I guess a timer would also work but that seems just as ugly.
All of this code goes in the code behind your workbook:
Option Explicit
Private Const NAMES_SHEET As String = "Hidden|Sheet|Names"
Private mNamesSheet As Worksheet
Private Sub Workbook_Open()
Dim b As Boolean
b = Application.ScreenUpdating
On Error Resume Next
Set mNamesSheet = ThisWorkbook.Worksheets(NAMES_SHEET)
On Error GoTo 0
If mNamesSheet Is Nothing Then
Application.ScreenUpdating = False
Set mNamesSheet = ThisWorkbook.Worksheets.Add
mNamesSheet.Name = NAMES_SHEET
mNamesSheet.Visible = xlSheetVeryHidden
End If
WriteNamesOfSheets
Application.ScreenUpdating = b
End Sub
Private Sub WriteNamesOfSheets()
Dim v() As Variant
Dim ws As Worksheet
Dim i As Integer
Dim b As Boolean
b = Application.EnableEvents
Application.EnableEvents = False
ReDim v(1 To ThisWorkbook.Worksheets.Count, 1 To 1)
mNamesSheet.Cells.Clear
i = 0
For Each ws In ThisWorkbook.Worksheets
If ws.Visible = xlSheetVisible Then
i = i + 1
v(i, 1) = "=" & ws.Name & "!A1"
End If
Next
mNamesSheet.Range("A1").Resize(UBound(v, 1)).Formula = v
Application.EnableEvents = b
End Sub
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Dim ws As Worksheet
Dim b As Boolean
On Error GoTo EH
b = Application.EnableEvents
Application.EnableEvents = False
WriteNamesOfSheets
For Each ws In ThisWorkbook.Worksheets
If ws.Visible = xlSheetVisible Then
'
'Populate your combobox here with ws.Name
'
End If
Next
Application.EnableEvents = b
Exit Sub
EH:
Err.Clear
End Sub

Showing hidden column in another sheet

I am having trouble finding how to "show" a hidden column in another sheet with VBA.I am currently studying VBA and I wanted to have a hide/unhide code for every case, but this one is missing. Any suggestions?
My (updated) code is here:
Private Sub CommandButton1_Click()
'To Hide Sheet 2
Worksheets("Sheet2").Visible = False
'To Hide Rows 22 to 25
Rows("22:25").EntireRow.Hidden = True
'To Hide Columns E to G
Columns(":G").EntireColumn.Hidden = True
'More specific hidding (inside a different sheet)
Worksheets("Sheet3").Columns("A:G").EntireColumn.Hidden = True
End Sub
Public Sub UnHideAll()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Rows.Hidden = False
Columns.Hidden = False
Next ws
End Sub
Private Sub CommandButton2_Click()
UnHideAll
End Sub
Try
Sub UnHideAll()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
ws.Rows.Hidden = False
ws.Columns.Hidden = False
Next ws
End Sub
The point of the code is that you need to qualify Rows and Columns by the worksheet if you want them to refer to anything other than the active sheet. Prefixing them by ws. lets VBA know what sheet the rows and columns are on. Then in the code for the button just:
Private Sub CommandButton1_Click()
UnHideAll
End Sub
I've tested it a number of times using both manually columns, rows, and sheets, as well as when it was VBA doing the hiding, and it seems to work fine.

Delete worksheet in Excel using VBA

I have a macros that generates a number of workbooks. I would like the macros, at the start of the run, to check if the file contains 2 spreadsheets, and delete them if they exist.
The code I tried was:
If Sheet.Name = "ID Sheet" Then
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
End If
If Sheet.Name = "Summary" Then
Application.DisplayAlerts = False
Sheet.Delete
Application.DisplayAlerts = True
End If
This code is returning an error:
run time error #424, object required.
I probably have the wrong formatting, but if there is an easier way to do this, it would be very useful.
Consider:
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "ID Sheet" Or t = "Summary" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
NOTE:
Because we are deleting, we run the loop backwards.
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.
With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.
Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.
Dim book
Dim sht as Worksheet
set book= Workbooks("SomeBook.xlsx")
On Error Resume Next
Application.DisplayAlerts=False
Set sht = book.Worksheets("ID Sheet")
sht.Delete
Set sht = book.Worksheets("Summary")
sht.Delete
Application.DisplayAlerts=True
On Error GoTo 0
Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete
try this within your if statements:
Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True

Reorder hidden tabs in excel

At work, we've developed a tool using Excel and VBA. This tool has hidden sheets that will only be opened once the previous step is complete. One of the issues I'm running into from the previous coder is that the very last step, there is an extra button, let's call it A, that can be clicked. Based on the order of sheets the previous coder created, this sheet was second out of 10, and when A is clicked, its automatically goes to the second position.
Is there any way I can modify it to the the right most tab?
The problem I run into is when I get to the final step, I can manually move the tab to the right hand side, but that is only after I have finished my analysis, and can not go to the beginning, so it does not allow me to save.
This will move your hidden sheet to end of all visible sheets:
Sub test()
With Sheets("Sheet1")
.Visible = True
Sheets("Sheet1").Move After:=Sheets(Sheets.Count)
.Visible = False
End With
End Sub
And this will move your hidden sheet to the end of all hidden and visible sheets:
Sub moveHiddenSheet()
Dim ws, x, lastSheet
x = 0
For ws = Worksheets.Count To 0 Step -1
x = x + 1
If Sheets(Worksheets.Count - x).Visible = False Then
Sheets(ws).Visible = xlSheetVisible
lastSheet = Sheets(ws).Name
Exit For
End If
Next ws
With Sheets("Sheet1")
.Visible = True
Sheets("Sheet1").Move After:=Sheets(Worksheets.Count)
.Visible = False
End With
Sheets(lastSheet).Visible = False
End Sub