How to show form at start of function which closes at end of function? - forms

I have a function which may take some time to execute.
How can I have a small modal form to show at the start of the function which closes when the function finishes?

Say frmModal is the form you wish to show. At the start of your function put in
frmModal.Show
frmModal.refresh
At the end of your function put in
Unload frmModal

My favorite trick for this is to put the code that is run into the form that is displayed while it is running. Then when it is done call Unload Me
'Code in Form1
Call frmWait.Show(vbModal, Me)
'Code in frmWait
Private Sub Form_Activate()
'Do some work ...
Unload Me
End Sub

when you load the form modal (form1.show vbmodal) then subsequent code is not executed until the model form is closed
a simple way (without api) to simulate what you want is to show the form modeless, and temporary disable the other form
have a look at the differences between command1 and command2 in the following test project :
'3 forms :
' Form1 : name=Form1
' contains 2 command buttons with the name Command1 and Command2
' Form2 and Form3 contain nothing special
Option Explicit
Private Sub Command1_Click()
Dim lngEnd As Long
Form3.Show vbModal
lngEnd = Timer + 5
Do While Timer < lngEnd
Caption = CStr(Timer)
DoEvents
Loop
Unload Form3
End Sub
Private Sub Command2_Click()
Dim lngEnd As Long
Enabled = False
Form2.Show vbModeless, Me
lngEnd = Timer + 5
Do While Timer < lngEnd
Caption = CStr(Timer)
DoEvents
Loop
Enabled = True
Unload Form2
End Sub

Related

How do I add buttons to an MS Access form at run time with VBA and add code to the _Click() event

I need to add buttons to a form at run time for Access. When clicked each button will need to open a modal form with specific information based on the button clicked. So for instance, if I write a loop to create five buttons and name them button1, button2, button3, button4 and button5; how would I achieve the following:
Private Sub button1_Click()
Msgbox "Button 1 was Clicked"
End Sub
Private Sub button2_Click()
Msgbox "Button 2 was Clicked"
End Sub
Private Sub button3_Click()
Msgbox "Button 3 was Clicked"
End Sub
Private Sub button4_Click()
Msgbox "Button 4 was Clicked"
End Sub
Private Sub button5_Click()
Msgbox "Button 5 was Clicked"
End Sub
This is a simplified version of what I want to achieve but this is the gist of it. Am I thinking about this correctly? Is there better way?
I am using MS Access 2010.
Any help is appreciated. Thanks
Here is how you can create an Event Procedure (Click()) for a Control (Command Button) named cmdDemo on the Current Form
Dim ctl As Control
Dim mdl As Module
Dim frm As Form
Set ctl = Me![cmdDemo] 'Set a Reference to the Command Button
Set frm = Me 'Set a reference to the Form
Set mdl = Me.Module 'Set a Reference to the Form's Code Module
'Create a Click() Event Procedure for the Command Button cmdDemo
lngReturn = mdl.CreateEventProc("Click", ctl.Name)
'Insert a single Line of Code in the Event Procedure
mdl.InsertLines lngReturn + 1, "Msgbox ""Create Procedure Demo"""

Combobox is not filled when user form is initialised, but filled after closing and reopening form

For some odd reason, my combo boxes are not "preloaded" with content once the form is initialised, the user has to first close down the form and then open it again for the combo boxes to be prefilled. It's a bug that is starting to irritate the end user, any idea why would this happen? I've attached Boot to a button in my spreadsheet, which initialses the form. Code below:
In UserForm1
Private Sub UserForm1_Initialize()
Call GetPrimaryContact
Call GetSecondaryContact
End Sub
In Module1
Public itm1
Public itm2
Sub Boot()
UserForm1.Show
Call GetPrimaryContact
Call GetSecondaryContact
End Sub
Sub GetPrimaryContact()
Dim Col As New Collection
Dim i As Long
Dim CellVal As Variant
' Clear filters
ThisWorkbook.Sheets("Master").AutoFilter.ShowAllData
' Get last row
LastRow = ThisWorkbook.Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row
' Loop between all of column F to get unique values
For i = 3 To LastRow
CellVal = ThisWorkbook.Sheets("Master").Range("F" & i).Value
On Error Resume Next
Col.Add CellVal, Chr(34) & CellVal & Chr(34)
On Error GoTo 0
Next i
' Populate the first with primary contacts
For Each itm1 In Col
With UserForm1.ComboBox1
If IsEmpty(itm1) Then .AddItem "No Contact" Else .AddItem itm1
End With
Next
End Sub
Sub GetSecondaryContact()
Dim Col As New Collection
Dim i As Long
Dim CellVal As Variant
' Clear filters
ThisWorkbook.Sheets("Master").AutoFilter.ShowAllData
' Get last row
LastRow = ThisWorkbook.Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Row
' Loop between all of column F to get unique values
For i = 3 To LastRow
CellVal = ThisWorkbook.Sheets("Master").Range("G" & i).Value
On Error Resume Next
Col.Add CellVal, Chr(34) & CellVal & Chr(34)
On Error GoTo 0
Next i
' Populate the first with primary contacts
For Each itm2 In Col
With UserForm1.ComboBox2
If Not IsEmpty(itm2) Then .AddItem itm2
End With
Next
End Sub
You should call the functions GetPrimaryContact and GetSecondaryContact on the form initialize event, this way the control's will be loaded as intended. See the example code below.
Sub Boot()
UserForm1.Show
End Sub
Private Sub UserForm_Initialize()
Call GetPrimaryContact
Call GetSecondaryContact
End Sub
I think your problem is that your Initialize code has Userform1_Initialize. It should only be written like Userform_Initialize and it will work.
And in the Sub boot put userform1.show last instead of first, If you stepping with F8 you will see that when you come to FormShow it stops there so it doesnt load your "Calls" until you close it and thats why you have them next time you start.

Wanting to allow only 2 of the same form to be opened VB6

So far i have some code that allows a user to Hit F1 which loads a new form of the same properties and then hides the one the first one they had up, Hitting F2, allows the user to close the newly opened form and show the one they opened first. I would like a restriction that allows the user to open only 1 extra form if they hit F1 with 2 of the same forms open then a messagebox appears telling them to close the second form first otherwise allow it to be opened.
Here is what i have so far.
Private Sub Form_Load()
End Sub
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyF1
'hides the current form
Me.Hide
'loads a new form with the same properties
Dim f As New Form1
Load f
'shows this new form
f.Show
'says that the second form is open
fOpen = True
Case vbKeyF2
'closes the second form
Unload Me
'says that the second form is closed
fOpen = False
'shows the first form you were on
Form1.Show
End Select
End Sub
Private Sub Form_QueryUnload(cancel As Integer, unloadmode As Integer)
'if your hitting "X" on second form then just close form2
If fOpen = False Then
Form1.Show
Else
'if your hitting "X" on main form close everything
Unload Me
End If
End Sub
Maybe something like if fOpen = true then disallow the user to hit F1? Not quite sure, but im close.
Forgive me if my VB6 is a little off, but you need to enumerate though the Forms collection to check to see if your form is already open...
Dim frm As Form
For Each frm In Forms
If frm.Name = "myForm" Then frm.Show()
Next frm
See this.
-- EDIT --
Just while I think on, to tune your code you could use a numeric iteration...
Dim f As Integer
Dim t As Integer
t = Forms.Count - 1
For f = 0 To t
If Forms(f).Name = "myForm" Then Forms(f).Show()
Next frm
-- EDIT 2 --
Just a further note on this. You may also want to introduce a counter so that you can check to see if there are two fields as in your original post...
Dim frm As Form
Dim c As Integer
For Each frm In Forms
If frm.Name = "myForm" Then
c = c + 1
If c = 2 Then
frm.Show()
Exit For 'Speed up the search if there are lots of forms
End If
End if
Next frm

Excel VBA Form is not refreshing properly when a subform is closed

Good Afternoon. I've running into a situation I hope someone here can help with. I'm running Office 2010 on Windows XP and have an Excel worksheet that contains a button to show a modal form (Form01). Form01 contains 3 Listboxes of data. Double-Clicking a item in listbox2 will open another modal form (Form02) so the item can be modified. Unloading Form02 will save the data and call a couple of macros to adjust a named range on the host worksheet. This code is stored in a Module, not on the form.
This is where the problem occurs. When Form02 is unloaded and Form01 is accessable, I cannot select anything in listbox1 or listbox3 or buttons on Form01. I have to first select something in listbox2, then I have access to the other controls on the form. I've tried to .SetFocus on the other controls and add DoEvents after the Form02.Show 1 statement with no luck. The only workaround I've found is to hide and reshow Form01 which causes the screen to flicker. Application.ScreenUpdating = False and back to True doesn't seem to help either. I really need to figure out what the other controls are not accessible when Form02 is shown and then closed. Has anyone else experienced this behaviour or might have a suggestion?
Change this
Private Sub lstSiteMaster_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
If lstSiteMaster.ListCount = 0 Then Exit Sub
LoadFrmEditDataset Me.Controls("lstSiteMaster"), "SITE MASTER"
frmEditDataset.Show 1
Unload frmEditDataset
DoEvents
Me.lstSiteMaster.ListIndex = -1
Me.lstSiteList.ListIndex = -1
Me.lstMiniPOR.ListIndex = -1
'''BounceTheForm
End Sub
to
Private Sub lstSiteMaster_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
If lstSiteMaster.ListCount = 0 Then Exit Sub
LoadFrmEditDataset Me.Controls("lstSiteMaster"), "SITE MASTER"
frmEditDataset.Show 1
DoEvents
Me.lstSiteMaster.ListIndex = -1
Me.lstSiteList.ListIndex = -1
Me.lstMiniPOR.ListIndex = -1
'''BounceTheForm
End Sub
AND
this
Private Sub cmdApply_Click()
With Me
UpdateDataset .lblDataset, .lblECR, .lblFA, .lblFieldId, .txtFieldValue, .cboAction, .lblIndex + 2
End With
Me.Hide
End Sub
to
Private Sub cmdApply_Click()
With Me
UpdateDataset .lblDataset, .lblECR, .lblFA, .lblFieldId, .txtFieldValue, .cboAction, .lblIndex + 2
End With
Unload Me
End Sub

Execute code when form is closed in VBA (Excel 2007)

I would like to execute some code when a user closes a form using the x button in the top right corner of the window (I have the form load when the excel spreadsheet is opened, and it hides Excel. I want to exit excel once the form is closed, or at least show excel again so the user may exit it manually)
Looking at the form properties, the Unload property is not present, nor am I able to figure out how to make a function which executes when the form is closed.
Unfortunately, coding this in VB is not an option, it must be VBA.
I'm aware of the code needed to unhide Excel or quit it outright, just not how to tie it to the unload event.
You can use QueryClose event of the UserForm as follows:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
' Your codes
' Tip: If you want to prevent closing UserForm by Close (×) button in the right-top corner of the UserForm, just uncomment the following line:
' Cancel = True
End If
End Sub
You can also use vbFormControlMenu like this:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
'Your code goes here
End If
End Sub
A colleague was able to provide the answer, including example here for everybody else
Private Sub userform_terminate()
'Code goes here
End Sub
You can use Unload Me in VBA to close a form. Just put the code to close Excel immediately following that.
Private Sub Form_Unload(Cancel As Integer)
Dim msgRes As VbMsgBoxResult
msgRes = MsgBox("Exit form ?", vbYesNo)
If msgRes = vbYes Then
'optional code
ElseIf msgRes = vbNo Then
Cancel = True
End If
End Sub
I was able to prevent the form from closing when the X button was click using the following:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Cancel = MsgBox("Please confirm cancellation", vbOKCancel + vbQuestion) = vbCancel
End Sub
try something like this:-
Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _
Handles Form1.FormClosing
//Code you want to execute
End Sub