How to hide sheets in your excel file that are not filled in - vba

I have an excel that hides certain sheets when opening the document. So like
Private Sub Workbook_Open()
Worksheets("screen_2").Visible = xlHidden
Worksheets("screen_3").Visible = xlHidden
end sub
Now I have the case that someone fills in either sheet "screen_2" or "screen_3". Right now when someone has filled in either screen_2 of screen_3 sheet closes the document and reopen the excel sheet "screen_2" and "screen_3" are not visible.
What I would like to achieve is that the first time you open the excel document both sheets should be hidden but that when you fill in one of the two sheets that particular sheet should not be hidden when reopening the excel file.
So when I open the excel sheet and fill in screen_2, save, close en reopen the file "screen_2" sheet should be visible (and screen_3 hidden) and when I open the excel doc and fill in screen_3, save, close en reopen the file "screen_3" sheet should be visible (and screen_2 hidden)
Any thoughts on how I can get this working?

once you get through how to fill a hidden sheet, then you could use:
Private Sub Workbook_Open()
CheckIfHideSheet Worksheets("screen_2")
CheckIfHideSheet Worksheets("screen_3")
End Sub
Sub CheckIfHideSheet(sht As Worksheet)
With sht
If .UsedRange.Address = "$A$1" And IsEmpty(.Cells(1, 1)) Then .Visible = xlHidden
End With
End Sub

Related

VBA - Run-time error '1004'

A bit of context, this is my first time programming using VBA in excel,
and I'm trying to create a form that fills out a spreadsheet.
I'm currently getting the error message: "Run-time error '1004': Method 'Worksheets'of object '_Global' failed
I've searched online and have tried various solutions, but I think basically it comes down to a lack of understanding on my part.
Private Sub CommandButton1_Click()
'When pressing save, save values in spreedsheet locations
ActiveSheet.range("c8").Value = ContactName.Value
ActiveSheet.range("b19").Value = ModelNumber.Value
ActiveSheet.range("d19").Value = SerialNumber.Value
ActiveSheet.range("g19").Value = IncidentNumber.Value
ActiveSheet.range("j19").Value = Description.Value
ActiveSheet.range("c7").Value = PortLocation.Value
'save file
ActiveWorkbook.SaveAs Filename:= _
"D:\Users\611281\Downloads\Zebra\EmailMeToZebra.xlsx", FileFormat:=xlOpenXMLWorkbook, ReadOnlyRecommended:=False, CreateBackup:=False
End 'after pressing save, close down sheet.
End Sub
Private Sub UserForm_Initialize()
Me.PortLocation.List = Worksheets("Data lookup_ports").range("e3:e200").Value
Dim MyTempWkBk As Workbook
Dim MyCurrentWin As Window
Set MyCurrentWin = ActiveWindow
Set MyTempWkBk = Workbooks.Open("D:\Users\611281\Downloads\Zebra\GUI.xlsm")
MyCurrentWin.Activate 'Allows only a VERY brief flash of the opened workbook
MyTempWkBk.Windows.Visible = False 'Only necessary if you also need to prevent
'the user from manually accessing the opened
'workbook before it is closed.
'Operate on the new workbook, which is not visible to the user, then close it...
End Sub
Private Sub UserForm_Terminate()
End 'when pressing x, close down window, do not save.
End Sub
I'm getting the error on the code:
Me.PortLocation.List = Worksheets("Data lookup_ports").range("e3:e200").Value
Which is just me trying to populate a ListBox from a spreadsheet range
Have you tried naming the workbook? This is assuming the line with the error is referring to a cell range in thisworkbook. Also, make sure to check the name of the sheet you are referring to for exact spelling (if spelling appears correct, also check for lagging spaces.) Also, is the worksheet hidden? If so, this may need to be added before calling the sheet.
wb.sheets("Data lookup_ports").Visible = True
Can try the below edit in the meantime.
Private Sub UserForm_Initialize()
Dim MyTempWkBk As Workbook
Dim MyCurrentWin As Window
Dim WB as Workbook
Set WB = ThisWorkBook
wb.sheets("Data lookup_ports").Visible = True
Me.PortLocation.List = WB.Sheets("Data lookup_ports").Range("E3:E200").Value
Set MyCurrentWin = ActiveWindow
Set MyTempWkBk = Workbooks.Open("D:\Users\611281\Downloads\Zebra\GUI.xlsm")
MyCurrentWin.Activate
MyTempWkBk.Windows.Visible = False 'Only necessary if you also need to prevent
'the user from manually accessing the opened
'workbook before it is closed.
'Operate on the new workbook, which is not visible to the user, then close it...
End Sub
Private Sub UserForm_Terminate()
End 'when pressing x, close down window, do not save.
End Sub

Disable alert when manually deleting a sheet

Is there a way in VBA to disable the alert that pops up when MANUALLY deleting a sheet (right click sheet and delete)? I have seen Application.DisplayAlerts = False, however this seems to only work for me when deleting a sheet using VBA (Sheets("Sheet1").delete). I am trying to disable the alert for the whole workbook when you manually right click on a sheet and click delete. Thanks.
In case anyone else is looking for the same scenario:
...eliminate the need to confirm deleting a sheet when presenting the
workbook in meetings. While going through the sheets I often double
click on pivot tables to view detail, and I would like to eliminate
the pop-up alert when I delete the generated sheet...
If new sheets are generated only when double-clicking a pivot table, this might be a suitable solution
Placed in ThisWorkbook, the code bellow will delete any new sheets, when selecting a different sheet
Option Explicit
'Place this code in ThisWorkbook module
'Expects that all new sheets are generated by double-clicking a pivot table
Private pivotWs As Worksheet
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Set pivotWs = Sh
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
If Not pivotWs Is Nothing Then
If Sh.Name = pivotWs.Name Then
Application.DisplayAlerts = False
pivotWs.Delete
Set pivotWs = Nothing
Application.DisplayAlerts = True
End If
End If
End Sub

Adding Command Button allowing user to view hidden sheet

I am new to using Macros/VB in excel and in need of some help (in the simplest way you can instruct me)
I have a workbook with two sheets. I have already created a form on sheet 1 which will allow users to enter data which then is populated within a hidden sheet (sheet2).
I would like to add a button on sheet 1 for the user to view the hidden "list data" they have entered in sheet 2 but they cannot be able to edit the data - only view it.
Any help would be greatly appreciated.
Insert a shape (I prefer this over an ActiveX control) on the sheet with your form. I named the shape "Show data" and gave that same caption to the button. Now add the following code to a standard code module (one which VBE names like "Module1").
Option Explicit
Sub ShowData_Click()
' 25 Jul 2017
With ThisWorkbook.Worksheets("Jeanette")
.Visible = xlSheetVisible
.Activate
End With
End Sub
Change the name of the worksheet with the data to the name you have given that sheet in your project. Then right-click on the button (shape) and select "Assign macro". Assign the "ShowData_Click" macro. Now, when you click the button the hidden sheet will become visible and be activated.
In the code sheet for the data sheet (which is normally hidden), add the following to procedures.
Option Explicit
Dim ThisSheet As String
Private Sub Worksheet_Activate()
' 25 Jul 2017
ThisSheet = ActiveSheet.Name
End Sub
Private Sub Worksheet_Deactivate()
' 25 Jul 2017
On Error Resume Next
Worksheets(ThisSheet).Visible = xlSheetVeryHidden
End Sub
The first one will run whenever the sheet is activated which happens when the new button is pressed. It will remember the name of the sheet. This is so that you don't need to hard-code the name.
The second procedure will run whenever you activate another sheet in the workbook. It will hide the sheet again. So, you show the sheet by pressing the button and hide the sheet by selecting another sheet.
I'm not a friend of Excel's protection. So, I suggest another way to prevent users from modifying the data. Here is the code. Install it on the same code sheet where you already have the Activate and Deactivate procedures.
Private Sub Worksheet_Change(ByVal Target As Range)
' 25 Jul 2017
Static ShowMsg As Integer
With Application
.EnableEvents = False
.Undo
ShowMsg = ShowMsg + 1
If (ShowMsg Mod 3) = 1 Then
MsgBox "Data in this sheet may not be modified." & vbCr & _
"Your changes have been removed.", _
vbInformation, "Invalid action"
End If
.EnableEvents = True
End With
End Sub
This code will undo any change the user makes. The user will receive a message to this effect each third time he/she tries to modify something.

Excel 2013 - issue when closing multiple workbooks if one workbook is hidden

I've written a program in Excel VBA which uses a UserForm to enter data by the users. Specifically, it is a Telemarketing Tracker tool: the user fills in the details of the call in a text box on the UserForm and then clicks the relevant button to indicate whether it was a good or bad call, and can then continue with the next call.
This data is stored on a worksheet and our users often prefer to hide the workbook and just view the UserForm. I have developed a couple of methods of hiding the workbook. If there is just one workbook open, I hide the Excel Application. If there is more than one workbook open, I just hide the window. Here is the code I use for this:
Private Sub HideUnhideButton_Click() 'User clicks Hide/Unhide button
If Workbooks.Count > 1 Then
Windows(ThisWorkbook.Name).Visible = Not Windows(ThisWorkbook.Name).Visible
HideUnhideButton.Tag = Windows(ThisWorkbook.Name).Visible
Else
ThisWorkbook.Application.Visible = Not ThisWorkbook.Application.Visible
HideUnhideButton.Tag = ThisWorkbook.Application.Visible
End If
ThisWorkbook.Activate
End Sub
This works well but obviously certain issues arise when the user has the workbook hidden and then open a different Excel Workbook. I've worked round most of these issues, but there is one thing I can't seem to work out: if the Telemarketing workbook is hidden, with another workbook open, if I click the Close button, both workbooks try to close.
I've tried creating a class module with an Application Level event tracker so that all workbooks' close events are monitored. But my problem is that when I click the close button, the first workbook that tries to close is the hidden workbook. So I can catch the close event and prevent the hidden workbook from closing but if I set Cancel to True, it prevents all the workbooks from closing!
The only workaround I can think of is when the user tries to close a workbook, I cancel the Close Event and Unhide the hidden workbook. But I don't know how to identify which workbook the user was attempting to close - so I can't work out how to automatically close the correct workbook.
I have currently set up the WorkbookBeforeClose event as follows:
Public WithEvents A As Excel.Application
Private Sub A_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
If Workbooks.Count > 1 Then
If Windows(ThisWorkbook.Name).Visible = False Then
If Wb.Name = ThisWorkbook.Name Then
Cancel = True
End If
End If
End If
End Sub
If I step through this code, I find that the Wb.Name is the name of the Telemarketing Workbook (even though it's hidden) and the name of the workbook that the user is actually trying to close does not appear at all - as far as I can work out.
Can anyone make any further suggestions?
The other thing I should mention is that it needs to work over Excel 2013 and Excel 2010.
I'm sorry to post an answer to my own question so quickly. It sort of indicates I didn't do quite enough research beforehand. However, for anyone who has a similar problem, here's my solution. This code needs to be posted in a class module and an instance of the class needs to be created before it will work, of course.
Note: in the below example, "TT" relates to the Telemarketing Tracker
Public WithEvents A As Excel.Application
Private Sub A_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
Dim VIS As Boolean, myAW As Workbook
If Workbooks.Count > 1 Then 'if there is more than one workbook open...
If Windows(ThisWorkbook.Name).Visible = False Then 'and if TT is invisible...
If ActiveWorkbook.Name = ThisWorkbook.Name Then 'and if the workbook being closed is the TT.
Windows(ThisWorkbook.Name).Visible = True
Else 'more than one wb open, TT is invisible, and the workbook being closed is NOT the TT.
Set myAW = ActiveWorkbook
Cancel = True
Windows(ThisWorkbook.Name).Visible = True
Application.EnableEvents = False
myAW.Close
Application.EnableEvents = True
If TelesalesForm.HideUnhideButton.Tag = "False" Then 'NB: I use a tag on the Hide/Unhide button on the UserForm to store whether the workbook should be hidden or not.
If Workbooks.Count > 1 Then
Windows(ThisWorkbook.Name).Visible = False
Else
ThisWorkbook.Application.Visible = False
End If
End If
Exit Sub
End If
ElseIf ActiveWorkbook.Name <> ThisWorkbook.Name Then
'more than one workbook open and the TT is visible and the workbook being closed is NOT the TT
Exit Sub
End If
End If
'code gets to this point ONLY under the following circumstances:
'There is only one workbook open (i.e. the TT) OR
'There is more than one WB open and the WB being closed is the TT.
'The rest of the code goes here for managing the closing of the TT.
End Sub
If anyone thinks of any other embellishments or improvements to the code then I would be very glad to hear of them!

VBA Excel 2013 form closes when selecting from ComboBox

Can anyone see an issue in this block of code. I had no issues in 2010, but seem to be running into a lot when running VBA in 2013.
I have a control form that is activated from an excel sheet, which has several options, then this form is opened (form those options). The form opens, but when this first combobox selection is activated the form closes and essentially crashes.
Public Sub cmbSelectAccount_DropButtonClick()
Application.ScreenUpdating = False
Workbooks.Open Filename:="C:\Users\xxxxxx\Desktop\New folder\accounts.xlsx"
Sheets("Accounts").Activate
ActiveSheet.Range("a2:a199").Select
Me.cmbSelectAccount.List = Worksheets("Accounts").Range("a2:a199").Value
myAccount = Me.cmbSelectAccount.Value
Workbooks("Accounts").Close
End Sub
If I step through the code it works flawlessly. Any help is greatly appreciated.
Try this (UNTESTED)
Public Sub cmbSelectAccount_DropButtonClick()
Dim wb As Workbook
Application.ScreenUpdating = False
Set wb = Workbooks.Open(Filename:="C:\Users\xxxxxx\Desktop\New folder\accounts.xlsx")
DoEvents
Me.cmbSelectAccount.List = wb.sheets("Accounts").Range("a2:a199").Value
DoEvents
myAccount = Me.cmbSelectAccount.Value
wb.Close (False)
End Sub
there are a few quirks with Sheets vs Worksheets in Excel, and maybe in 2013 they tried to fix them. I'd try changing your 2 references to sheets and worksheets to all possible combinations, starting first with sheets, sheets then worksheets worksheets, then worksheets sheets