Hide sheets in Excel VBA - excel

I am trying to create an Tracker. Need help with these ideas:
When the Excel book is opened, it must show only the "Tracker" Worksheet. All other sheets need to be hidden. Now am using the code {sheet.visible = xlveryhidden} But the code is too long, I have to include each sheet name. I need help with a code to show only the Tracker sheet but to hide all other sheets in the workbook.
I've included two comboboxes as year and month. Also included a Command button OK & Cancel. When clicked on OK, it has to verify the IF condition and show a specific sheet. I have no issues with that. it is showing a specific sheet. But I need a single line code to hide all other sheets
I have also included a "New Tracker" Command button. When Clicked on it, it must include a New sheet. Also too let the user to rename it. This worksheet must also be hidden once saved.
I aware the process is simple, but not sure how to complete it.

To hide all but the Tracker worksheet
Sub hidesheets()
Dim ws As Worksheet, wb As Workbook 'Create the variables we'll use for our worksheet and workbook objects.
Set wb = Excel.ActiveWorkbook 'Set the workbook variable to equal the active workbook. This can also be set to equal a named workbook if you want.
For Each ws In wb.Worksheets 'Loop through each worksheet in the workbook.
If Not ws.Name = "Tracker" Then 'If the worksheet's name isn't "Tracker" then...
ws.Visible = xlSheetVeryHidden 'Set it to very hidden.
Else 'If it is the "Tracker" worksheet, then ...
ws.Visible = xlSheetVisible 'Set it to visible.
End If 'End the IF/THEN statement.
Next ws 'Repeat for the next worksheet in the workbook.
End Sub
You'll have to modify this if you want it to work with a command button or do something with another worksheet. But it should get you started. I'd do it but I don't quite have the time right now.

Related

Copy/Paste worksheet to new workbook without that worksheet's VBA code

What I want to do is to create a normal Excel workbook (.xlsx) where I summarize the inputs/outputs of some simulations by copying some sheets from a Macro-enabled workbook (.xlsm) and pasting in a normal Excel workbook. The original sheets have macros, shapes, named ranges, dropdown lists, and some formatting. I want some properties of the sheets to come over to the new workbook (named ranges, row and column formatting, cell formatting) but not others (shapes, dropdown lists, macros). I also have to distribute the .xlsm workbook to other users, so I want a solution that doesn't require the user to grant permissions.
If I copy/paste like below, then I get all the properties of the worksheet to come over to the new workbook. I have figured out how to delete shapes and remove dropdown list formatting from the sheet in the new workbook, but I can't remove the worksheet's VBA code without modifying the VBA references.
If I paste special, then I can avoid bringing over the worksheet's VBA code, but I can't bring over the named ranges.
CopySheetToWB(sht as string, wb_New as workbook)
Dim sht_Name as string, rng As Range, shp as shape
Dim ws As Worksheet, wb As Workbook, ws_New As Worksheet
' set sheet in CURRENT wb
Set wb = ThisWorkbook
Set ws = wb.Worksheets(sht)
' copy/paste sheet to NEW wb
ws.Copy after:=wb_New.Sheets(wb_New.Sheets.Count)
' delete shapes from NEW ws
Set ws_New = wb_New.Worksheets(sht)
For Each shp In ws_New.Shapes
shp.Delete
Next shp
' remove dropdown lists from copied sheet
ws_New.Cells.Validation.Delete
End Sub
The answer to my problem turned out to be quite simple. My old code that wasn't working and my new code that is working. If you save the file type correctly, then the macros in the worksheets are not a problem as they are removed.
wb_New.SaveAs FileName:=str_fName, FileFormat:=xlWorkbookNormal 'old code
wb_New.SaveAs FileName:=str_fName, FileFormat:=51 'new code
Also make sure to include the file extension in str_fName. VBA doesn't automatically append the correct file extension based on the FileFormat you choose.

"Runtime Error 1004: Copy method of worksheet class failed " in VBA on first copy attempt

(Sorry in advance for my poor English: not first Language :) )
I am writing a VBA Excel 2003 routine that runs through 50+ worksheets in a file, copies the worksheets (just as a temp copy) one by one and then performs actions on them before removing these temporary copies and returning the result of it's calculations on the worksheets content.
To be more precise: the code is called from an external file with a single (hidden) worksheet inside. When I open the file it runs a code to create a new toolbar in Excel, when I press a button on the toolbar, the code I have described above runs.
I know that not saving a file and performing many and many copies triggers this error, but now it is triggering at the first attempt (I have closed and reopened everything multiple times to be sure I am not keeping the not saved situation with me).
This is the code triggering the problem, I am sorry for poor formatting:
ActiveWorkbook.Worksheets("NAME OF THE FIRST WORKSHEET I WANT TO COPY").Copy ThisWorkbook.Worksheets("HiddenSheet")
Disclamer: the name of the worksheet is found by a For..Next cycle through the ActiveWorkbook.Worksheets array, but the code is not working even if i hard-code the name myself.
Here is a larger chunk of the code, to be clearer:
Set sourceWorkbook = ActiveWorkbook
For index = 1 To sourceWorkbook.Worksheets.Count
sourceWorkbook.Activate 'not sure if this is even needed
Set currWorksheet = sourceWorkbook.Worksheets(index)
currWorksheet.Copy ThisWorkbook.Worksheets("HiddenSheet")
Next index
The result is now consistently:
Run-time Error '1004'
Copy method of worksheet class failed.
I thank everybody in advance for the help!
Some useful guidelines:
Option Explicit
'Copy sheet
Sub CopySheet()
Dim ws1 As Workbook, ws2 As Workbook
'It's better to declare sheets and avoid activate
Set ws1 = Workbooks("Book1")
Set ws2 = Workbooks("Book2")
'Copy sheet "Test" from ws1(Book1) to ws2 (Book2) after all sheets
ws1.Worksheets("Test").Copy After:=ws2.Worksheets(Sheets.Count)
End Sub
Option Explicit
'Copy a range
Sub CopyRange()
Dim ws1 As Workbook, ws2 As Workbook
'It's better to declare sheets and avoid activate
Set ws1 = Workbooks("Book1")
Set ws2 = Workbooks("Book2")
'Copy from ws1(Book1), sheet "Test" & range A1:A5 to ws2 (Book2), sheet "sheet1" & range A1
ws1.Worksheets("Test").Range("A1:A5").Copy
ws2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste:=xlPasteValues
End Sub

Copy formatting to macro

I have a workbook that the workbook formatting is changed regularly, however once changed (maybe weekly or monthly) then going forward until it is changed again a macro needs to replicate that format. Changing the VBA to account for the new formatting each time is very time consuming. Is it possible to format a workbook and then copy the formatting easily to VBA (after the fact not like a macro record) for future use?
In the past I have since used a hidden sheet within the workbook where the macro runs and I essentially copy/paste that into the sheet I am working with. This works but has the downside of when making changes I first need to copy data over to the "template" sheet to ensure everything is correctly aligned with new data.
Possibly some kind of macro that iterates through all cells of a range and outputs to the immediate window the VBA code needed to re-create the formatting?
Basically any ideas will help :)
There are so many formatting options that simply storing them as separate options will take far more space than just a duplicate template sheet. Just run the first code to update your template, and the second to copy it back:
option Explicit
Const TemplatesheetName = "mytemplate"
Sub CopyFormatting
dim ws as worksheet
dim source as worksheet
set source = activesheet
for each ws in worksheets
if ws.name = templatesheetname then
exit for
end if
next ws
if ws is nothing then
set ws = worksheets.add
ws.name = templatesheetname
end if
ws.usedrange.clearformats
source.usedrange.copy
ws.range("a1").pastespecial xlpasteformats
ws.visible = xlveryhidden
end sub
Sub BringBackFormats
dim ws as worksheet
for each ws in worksheets
if ws.name = templatesheetname then
exit for
end if
next ws
if ws is nothing then
msgbox "No template found",vbokonly,"Unabl;e to run"
else
ws.cells.copy
activesheet.range("a1").pastespecial xlpasteformats
end if
exit sub
(written on my phone, can't check the code, there may be typos)

How do I get the selected tab in a workbook (but not the ActiveWorkbook)?

I hope this is a simple question...
My understanding is that "ActiveWorkbook" returns the currently active workbook, even if the macro was run in a different workbook (this is why I almost always use "ThisWorkbook" instead).
And "ActiveSheet" returns the currently active worksheet, even if the macro was run in a different workbook (or different worksheet).
So how can I get the worksheet which currently has focus within a specific workbook, even if that workbook is not the currently active one?
You can do this by fully qualifying .ActiveSheet
Example:
Private Sub test()
Dim wb As Workbook
Set wb = Workbooks.Add
'Change the name of Sheet1 in the second workbook
'so it's not confused with Sheet1 in the first workbook.
wb.Sheets("Sheet1").Name = "Foo"
ThisWorkbook.Activate
MsgBox wb.ActiveSheet.Name
End Sub

How to disable the display of pagebreaks for the workbook in Excel VBA?

I am able to disable the display of page breaks for the single worksheet in Excel,but i want to disable for the whole workbook at a time .Please someone help me to disable the display of pagebreaks for the workbook by using VBA.
This has already been answered, but here's what you need:
Sub DisablePagebreak()
Dim ws As Worksheet
For Each ws In Worksheets
ws.DisplayPageBreaks = False
Next
End Sub
Worksheets is the collection of all Worksheets from the current Workbook. As the name's implying .DisplayPageBreaks hides/shows the page breaks.

Resources