Userform1 ComandButton1 code is similar to this (contains more lines of CheckBox checks):
Sub CommandButton1_Click()
Application.DisplayAlerts = False
Set WB = ActiveWorkbook
If CheckBox25.Value = False Then
WB.sheets("PQC 1025").Delete
Else: CheckBox25.Value = True
End If
Unload Me
End
Application.DisplayAlerts = True
End Sub
The second macro will be a Format/Print macro:
Sub Format_Print()
Dim ws As Variant
For Each ws In Workbook
ActiveSheet.PageSetup.LeftFooter = "" & Format(DateTime.Now(), "yyyyMMdd hh:mm:ss")
ActiveSheet.PageSetup.RightFooter = "Page &P of &N"
Next
For Each ws In Workbook
ActiveSheet.PrintOut Copies:=1, Collate:=True
Next
End Sub
I honestly don't know where to start. I'm not a strong coder and it took me a while to get as far as I did.
I would like this macro to automatically happen when Userform1 unloads after use of CommandButton1 (the Okay button). I do not want this second macro to start automatically when CommandButton2 is used to unload Userform1 (the Cancel button).
Any input on how I might try this would be helpful.
I ended up making a new button on the main form to format/print. I fixed a few of the issues I was having with my initial format/print code, removed all of the dimension and setting and simply said "sheets.select" which was the simple fix to object errors.
I had no check that people selected the correct sheets, so I figured this was a safer approach.
Related
I have set up a new, empty, modeless userform, to fix my problem with the least amount of code involved.
For when the workbook is opened, the following code is executed to hide Excel and show the userform. It's the only code for the workbook.
Private Sub Workbook_Open()
UserForm1.Show
If Application.Windows.Count <> 1 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
End Sub
I have an empty userform with one single button. The only code for this userform is:
Private Sub CommandButton1_Click()
Application.Windows("test.xlsm").Visible = True
Application.Visible = True
Unload Me
End Sub
The last thing is a button on the first worksheet, to start the same process as when the workbook is opened. Its code:
Sub Button1_Click()
UserForm1.Show
If Application.Windows.Count <> 1 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
End Sub
Now my problem:
When I open the workbook, the userform shows up, but excel and the active window stay visible as well. However, if I click the button on the worksheet, Excel, or the window, are hidden as they should. Also, Excel, not the userform, has focus after loading everything.
The first time I ran this, it worked fine. I suspect changing the ShowModal setting in the editor screwed it up somehow, but that's just me guessing. Anyway, it doesn't work anymore as intended, no matter the modal setting now.
If I just run
Application.Visible = False
instead of the "if"-clause, Excel still stays visible and of course so does the active window.
This is driving me nuts.
What am I missing?
Edit: Link to my test file: Test File on my Dropbox
Might have to start it twice, because when the macros are blocked at startup and only activated after excel has completely loaded, the code works as intended.
Edit: I was able to test this on an excel 2010 pc and there the problem doesn't exist. So it might have something to do with the way newer Office Apps handle stuff.
I found myself having the exact same problem - modeless form opened with Workbook_Open() event that's also supposed to hide excel app (working on Excel 2016, 32bit).
The reason why it's working with UserForm property ShowModal set to True is because: the execution is suspended - it's waiting for user to interact with the UserForm that was shown.
If we change ShowModal to False (or call UserForm.Show vbModeless) then the execution is never suspended and once we reach End Sub of our Workbook_Open(), Excel appears to set Application.Visible = True on its own.
Only solution I've found thus far is this one - basically you suspend the execution by adding an infinite loop so Excel only gets to end of this event once you get rid of (Unload/Hide) the form that was shown previously.
My version looks like this:
Private Sub Workbook_Open()
Dim App As Object
Set App = startMenu
App.Show vbModeless
While App.Visible
DoEvents
Wend
End Sub
Then just to make sure that Excel is closed once that modeless UserForm is closed I've added this:
Private Sub UserForm_Terminate()
CloseApp
End Sub
Public Sub CloseApp()
ThisWorkbook.Saved = True
If Not OtherWorkbooksOpen Then
Application.Quit
Else
ThisWorkbook.Close
End If
End Sub
Public Function OtherWorkbooksOpen()
If Application.Workbooks.Count > 1 Then
OtherWorkbooksOpen = True
Else
OtherWorkbooksOpen = False
End If
End Function
EDIT:
Solution without infinite loop - schedule hiding of Excel:
Private Sub Workbook_Open()
Dim App As Object
Set App = startMenu
App.Show
If Not OtherWorkbooksOpen Then
Application.OnTime Now + TimeValue("00:00:01"), "HideExcel"
End If
End Sub
I think the userform1.show needs to be called after the execution of if statement.
Private Sub Workbook_Open()
If Application.Windows.Count <> 1 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
UserForm1.Show
End Sub
Not an answer, but I can't post this as a comment. This works for me - the user form appears, the application is hidden. I used "<>2" as I have a personal workbook. Can you confirm what happens for you?
Private Sub Workbook_Open()
If Application.Windows.Count <> 2 Then
Application.Windows("test.xlsm").Visible = False
Else
Application.Visible = False
End If
UserForm1.Show False
End Sub
I had the same issue, but I notice the form loads before the excel file. So I put a redundancy calling the application.visible = false, in the form.
Basically after clicking anything in the form, it will call the application.visible = false and the excel window will hide.
When a modeless userform gets loaded, the code in it (except for the Userform_Initialize sub) sometimes does not execute and the main code which calls the userform continues running.
I had it solved, somehow, but this was in the latest update of my program which unfortunately got corrupted.
Sub start() 'shortened drastically, but accurate
'....
If UBound(rs.GetRows(1000000), 2) + 1 < 6 Then
.Close SaveChanges:=False
ThisWorkbook.Sheets("Start").Range("DA1").Value = "1"
ThisWorkbook.Sheets("Start").Range("DA2").Value = MachineNr
UserForm1.Show vbModeless
GoTo ExSub
End If
'...
ExSub:
End Sub
And in the userform module:
Private Sub UserForm_Initialize()
Dim wb As Workbook
If ThisWorkbook.Sheets("Start").Bijwerken = "ja" Then
Me.CommandButton2.Caption = "Cancel"
Me.Label1.Caption = "Select a file to update"
bestand = ""
With Me.ComboBox1
For Each wb In Application.Workbooks
If Not wb.Name = ThisWorkbook.Name Then
For Each sht In wb.Sheets
If sht.Name = "AssetTypeTask" Then
.AddItem wb.Name
Exit For
End If
Next sht
End If
Next wb
End With
Else
bestand = ""
With Me.ComboBox1
For Each wb In Application.Workbooks
If Not wb.Name = ThisWorkbook.Name Then
.AddItem wb.Name
End If
Next wb
End With
End If
End Sub
The code runs through the Userform_Initialize sub without issues, but the userform does not appear at the front of the screen and the code continues at GoTo ExSub which then ends the code execution. The userform stays open but closes as I press one of the commandbuttons on it.
"Code execution will also continue in the background while a modeless
form is shown."
This is what brought me back on my feet. I knew this but had forgotten about it as I firmly believe and still believe that in previous versions of my program I had a modeless UF running that DID interrupt the code.
I ended up solving the issue of the running code by adding a simple loop to check the state of the UF
Do Until Userform1.Visible = False
DoEvents
Loop
This is a slight drawback for the CPU of course, so not ideal, but since this is not a very intensive part of the program, it will do.
The UserForm I use in this instance has to be modeless, because the user needs to be able to scroll through the userform to make sure what they are populating the controls in the UF with is correct. This is not programmable.
If anyone has any other ways of achieving this, please let me know.
Scenario
I have a userform whereby excel workbook will be hidden while opening using the following method of Application.Visible = False. These are the codes
My userform
show excel button is Commandbutton1
hide excel button is Commandbutton2
This workbook
Codes
Private Sub Workbook_Open()
Call hideExcel
UserForm1.Show
End Sub
Userform1
Codes
Private Sub CommandButton1_Click()
If Workbooks.Count > 1 Then
Windows(ThisWorkbook.Name).Visible = True
Else
Application.Visible = True
End If
End Sub
Private Sub CommandButton2_Click()
Call hideExcel
End Sub
Sub UserForm_Initialize()
Call hideExcel
End Sub
Private Sub UserForm_Terminate()
If Workbooks.Count > 1 Then
Windows(ThisWorkbook.Name).Visible = True
Else
Application.Visible = True
End If
End Sub
Sub userform_click()
Call hideExcel
End Sub
Module
Codes
Sub hideExcel()
If Workbooks.Count > 1 Then
Windows(ThisWorkbook.Name).Visible = False
Else
Application.Visible = False
End If
End Sub
Problem
The problem I am facing is
Open my macro and userform activated. Lets call this file A
Then open another workbook. Lets call this file B
Tried to close file B while workbook A is hidden. But there is a prompt to close file A also and eventually all excel will be closing including my macro file which is A.
Does anyone know what is the problem here?
I don't understand where the problem is? If you are closing last visible (not hidden) workbook, Excel also tries to close all other open workbooks (even if they're hidden). And I think it's normal Excel behavior. You can only avoid to see a prompt, e.g. by setting up Workbook.Saved property to True or by setting up Application.DisplayAlerts property to False or just by saving workbook before closing.
If you don't want to close hidden workbook you just have to make it visible before closing the second workbook.
New here and I just started to teach myself coding. I have a workbook that has roughly 14 tabs/worksheets for employees to enter their hours worked per day. On a "Summary" tab and want to create a macro button for each employee to click on to view his/her tab. These employee tabs are hidden and all I want the action to do is unhide and then hide when the employee clicks their button.
Unfortunately, I receive an Ambiguous Error message and I created a module per employee. I assume I need to somehow "stack" code, but again am totally new to coding. Below is a sample of my code
Private Sub ShowHideWorksheets()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
you need to correctly put it behind a button. When you insert the button into the page, right click it and assign macro. The code would look like
Sub Button1_Click()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
Basically you wish to toggle visibility for a worksheet.
Assuming that you know which Sheet is going to be triggered, it is something like this:
Public Sub TriggerSheetVisibility(worksheetname as string)
Dim ws as WorkSheet
On Error Resume Next 'To avoid subscript out of range error if a worksheetname is passed that doesn't exit
Set ws = Worksheets(worksheetname)
On Error Goto 0
If Not ws Is Nothing Then 'Only when the worksheet exists, we can execute the rest of this sub:
If ws.Visible = True then
ws.Visible = False
Else
ws.Visible = True
End If
End If
End Sub
Also see https://msdn.microsoft.com/en-us/library/office/ff197786.aspx
This is also an acceptable approach? Prolly long winded though
Private Sub CommandButton1_Click()
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If sheet.Name <> CommandButton1.Caption Then
sheet.Visible = False
End If
If sheet.Name = CommandButton1.Caption Then
sheet.Visible = True
End If
Next sheet
End Sub
However I like this better due to the fact you only need one button
Private Sub CommandButton1_Click()
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If sheet.Name <> Environ("USERNAME") Then
sheet.Visible = False
End If
If sheet.Name = Environ("USERNAME") Then
sheet.Visible = True
End If
Next sheet
End Sub
If you change Private to Public it should work. I'm presuming you're just creating macros at this point to get base functionality to work. You can hide (as the code you've posted) and unhide like this:
' This first macro actually just makes the worksheet visible and then
' invisible each time you execute it - so I'm not sure if
' that's what you're after
Public Sub ShowHideWorksheets()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
' If it's invisible you can do this.
Public Sub ShowWorksheets()
Sheets("EMPLOYEE 1").Visible = True
End Sub
' Basically that should give you an idea of how to proceed.
As the title say I've been having one particular problem with my userform. When I close it (with a command button) an error pops on Userform.Hide inside the Workbook_Deactivate event.
This is the code on the Userform_initialize event:
All variables in here are global
VBA:
Private Sub Userform_Initialize()
subRemoveCloseButton Me
Set pagina = ThisWorkbook.Worksheets("Ruta")
Set libro = Workbooks.Open(pagina.Range("B4").Value, False, True)
Set pagina2 = libro.Worksheets("GLOBAL")
pasadas = 0
If pagina2.AutoFilterMode Then
If pagina2.FilterMode Then
pagina2.ShowAllData
End If
ElseIf pagina2.FilterMode Then
pagina2.ShowAllData
End If
pagina2.Columns("A:IV").EntireColumn.Hidden = False
lastRow = pagina2.Cells(pagina2.Rows.Count, "B").End(xlUp).Row
Call RemoveDuplicates
With Me.ImagenDatos
.ScrollBars = fmScrollBarsBoth
'Change 8.5 to suit your needs
.ScrollHeight = .InsideHeight * 5
.ScrollWidth = .InsideWidth * 3
End With
End Sub
Then in the CommandButton_Click event I have this:
VBA:
Private Sub BotonCerrar_Click()
Unload Consultas
libro.Saved = True
libro.Close
ThisWorkbook.Close
End Sub
The error, as already commented, comes from this:
VBA:
Private Sub Workbook_Deactivate()
Consultas.Hide
End Sub
If I comment that single line the Userform closes with no problem but I need it so the userform (Consultas) hides when the user switches between workbooks.
The error message says: Object variable or With block variable not set (Error 91)
Anyone have a clue on what's going wrong?
This is my first post and if something else is needed just let me know.
I would appreciate any help on this.
EDIT: I have more code but I think this is pretty much the essential as all I do is open the excel workbook, then the userform shows and then I click the button that closes the userform
So this is how I solved this:
Before trying to hide the userform Consultas on the Workbook_Deactivate event I first checked if the userform was visible with the link provided by #Ralph.
That solved part of the problem but then the error moved to the part where I close libro :
Private Sub BotonCerrar_Click()
Unload Consultas
libro.Saved = True
libro.Close
ThisWorkbook.Close
End Sub
The error persisted even before unloading the userform as suggested by #A.S.H but I fixed it calling Application.Workbooks(libro.Name).Close False instead of libro.close False (If someone could explain this to me I would really appreciated it)
The final code is the following:
Private Sub BotonCerrar_Click()
Dim wb As Workbook
Dim otrolibro As Boolean
otrolibro = False
Application.Workbooks(libro.Name).Close False
Unload Consultas
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then
otrolibro = True
Exit For
End If
Next wb
If otrolibro = True Then
ThisWorkbook.Close False
Else
ThisWorkbook.Saved = True
Application.Quit
End If
End Sub
The For cicle is to quit the excel application if there is not another Workbook open because if I just close all Workbooks, an Excel window remains open with nothing on it.