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

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!

Related

Workbook not opening at startup (splash screen frozen)

I use Excel 2016. The file I am using runs some code in workbook Open event handler.
Depending on what the code does the workbook may never get opened (visible).
in Workbook_Open the event handler establishes a connection with a data base and load some data eventually warn the user if an error occurs for instance.
Establishing the connection with a data base and load some data works most of the time. Some times it does not and the Excel splash screen remains on the screen for ever. After closing the splash screen clicking on the close cross, the Excel process continues running in the background.
If an error occurs I don't see the pop up form which is opened to warn the user as long as the workbook is not visible.
when I kill the process an reopen Excel (not the workbook), Excel suggest to retrieve the file which was opened earlier proving somehow that it has in deed been opened.
The second process just does not work unless the workbook is visible. If I run Excel and then open the workbook it s ok (in case an error occurs the warning pop up form is opened).
If Excel is closed and i open the workbook it does not work (splash screen frozen).
what is the proper way to start a VBA application where It is necessary to manage some cosmetics tasks (show some sheets, hide some other) and run a connection to a data base?
Here is a simplified version of the code (can't provide it all - too complex - too long)
In this code the function bConnectToTheDatabase is forced to return False which make the bLogin function useless (the code is not provided for this reason).
Private mLoginForm As frmLgn ' a form to login the application (see image)
Private mCustomMsgBox As frmMsgBox ' a form to display custom messages (see image)
Public Const gsPFU_VBA_PWD as String = "my secret password"
Public Const gsBLANK_WKS_NAME As String = "Blank"
Private Sub Workbook_Open()
'
Call HidShowSomeSheets()
' start the application up
Call LoginIntoTheApplication()
End Sub
' hide all sheets but the one named gsBLANK_WKS_NAME
' protect/unprotect to chnage visibility
Sub HidShowSomeSheets()
With Application.Workbooks(ThisWorkbook.Name())
.Unprotect (gsPFU_VBA_PWD)
.Sheets(gsBLANK_WKS_NAME).Visible = xlSheetVisible
For Each wks In .Sheets
With wks
.Unprotect (gsPFU_VBA_PWD)
End With
Next wks
For Each wks In .Sheets
With wks
If (StrComp(gsBLANK_WKS_NAME, .Name) <> 0) Then
.Unprotect (gsPFU_VBA_PWD)
On Error Resume Next
.Visible = xlSheetVeryHidden
Else
.Protect (gsPFU_VBA_PWD)
.Activate
End If
End With
Next wks
.Protect (gsPFU_VBA_PWD)
End With
End Sub
Sub LoginIntoTheApplication()
if( bConnectToTheDatabase() ) then
call bLogin
else
'create a custom form (it has it own even handler - block the execution flow)
'set mCustomMsgBox= new frmMsgBox
'mCustomMsgBox.Show vbModeless 'this does not work
MsgBox "something went wrong" 'this works
end if
end Sub
Function bLogin() as Boolean
'login into the application
End Function
Function bConnectToTheDatabase() as Boolean
'do the connection
'get the data
'etc ....
bConnectToTheDatabase= False 'fore it to False for the purpose of the explanation
End Function
The login form
The custom message box

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

Excel VBA - How to use worksheet event in add-in module?

I am new to Excel Add-ins and I am not sure how to write mi programm.
I would like to put in an add-in a code so that, when the workbook that uses the add-in is opened, it creates a sheet named "mainSheet".
I can use the event handler in the Workbook, but is it possible to put the code in the module of the add-in and still be able to run it?
I found this on the "Automate Excel" web site. Hope this helps
The following code works opening a workbook. It automatically adds a new sheet and labels it with the name. It also checks to see that the sheet doesn’t already exist – to allow for the possibility of it being opened more than once a day.
This code makes use of the Workbook Open Event and must be placed in the workbook module under the “Open work Book” event. The function Sheet_Exists must be placed in a module and this checks whether or not the sheet exists:
Private Sub Workbook_Open()
Dim New_Sheet_Name As String
New_Sheet_Name = "mainSheet"
If Sheet_Exists(New_Sheet_Name) = False Then
With Workbook
Worksheets.Add().Name = New_Sheet_Name
End With
End If
End Sub
==
Function Sheet_Exists(WorkSheet_Name As String) As Boolean
Dim Work_sheet As Worksheet
Sheet_Exists = False
For Each Work_sheet In ThisWorkbook.Worksheets
If Work_sheet.Name = WorkSheet_Name Then
Sheet_Exists = True
End If
Next
End Function

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