Close current form and open a different one in Access? - forms

I'm trying to create a macro that closes the current form and opens the main form.
Since I have so many forms and I need the same button with this macro in all of them, I want to create a macro just once and not for each form separately.
Is there any way to do so?

Create a code module and add the following function:
Public Sub CloseMeAndOpenMain(frmMe As Form)
DoCmd.Close acForm, frmMe.Name
DoCmd.OpenForm "frmMain" 'Replace this with the actual name of your Main form
End Sub
Now, each time you have a button that should close the current form and open the "frmMain" form, you would write the click event handler like so:
Private Sub btnCloseForm_Click()
CloseMeAndOpenMain Me
End Sub
Me is a reference to the current form, and each form has a Name property. Therefore you can write a function to close it without having to hardcode the name as a String (except of course for the main form).

Related

Open Form to a value selected on ComboBox - Ms Acces

I want to open a form to a specific record based on the value is selected on a comboBox. I have written a code and its working, but before opening the form it shows a dialogue box with input field asking for the parameter i want for the form which i dont want the VB code to ask.
DoCmd.OpenForm "Final_Exam", acNormal, , "[admclass] = " & Me.Combo4.Value & ""
This is the code i have written and the requirement is that on clicking the button the form opens without any dialogue box asking for parameter. thanksa
What I've found is the best way to open one form from another is to use OpenArgs. When opening Form 2 from Form 1's button, use code like this:
Private Sub cmdOpenOtherForm_Click()
DoCmd.OpenForm FormName:="frmOtherForm", OpenArgs:=Me.Combo4.Value
End Sub
Then, in the Load event of Form 2, use the openargs to set up your filter:
Private Sub Form_Load()
If Not IsNull(Me.OpenArgs) Then
Me.Filter="[admclass]=""" & Me.OpenArgs & """"
Me.FilterOn = True
End If
End Sub
If the field you're filtering on is a text field, make sure to properly escape double quotes (as is done above).

Open a VBA Multi Tab Form in Excel to a specific tab

I'm confident this is going to be a very easy answer for anyone with VBA knowledge (which I don't have). I have a form built for Excel in VBA. It's a multitab form and I want to have the form consistently open on the first tab when the "Open Form X" button is clicked in Excel. Let's call the form "Form1" and the tab "IDTab"
I have tried the following code but neither has worked:
Private Sub GetFormButton_Click()
Form1.Show With MultiPage1 Value = 0
End Sub
AND
Private Sub BackToExclu_Click()
With MultiPage1
.Value = (.Value - 1) Mod (.Pages.Count)
End With
End Sub
You were very close, actually :)
If you place the code into the Initiliaze Event within the userform itself, it will always display the first page of the multi-page control any time the form is loaded.
Private Sub UserForm_Initialize()
Me.MultiPage1.Value = 0
End Sub
To place this code into the UserForm Module, right click on the UserForm object in the VBE and click View Code.
Then your button click code would just be:
Private Sub GetFormButton_Click()
Form1.Show
End Sub
Open y
open your excel workbook
find your form
right click the name of the form
select "show program code"
In the programcode for the form enter the code below:
Private Sub UserForm_Activate()
MultiPage1.Pages("IDTab").Enabled = True
End Sub
Mind you: MultiPage1 might be called differently in your form. MultiPage1 is the default name of the container holding the tabbed pages in my excel workbook. In the properety window you can find the actual name of that container.

How do I send data back to the parent form, such as a list or value, in Visual Basic?

I have a form that I open to have the user select data from. Then I want to send that data back to the form that was spawned that data. Here is my code from the parent form:
Private Sub bttn_AW_SelectUnits_Click(sender As Object, e As EventArgs) Handles bttn_AW_SelectUnits.Click
'TODO: Capture output from next menu
Dim changeUnits As New AuditWizardUnits
changeUnits.ShowDialog()
End Sub
I could have it spawn a new form, but I have multiple forms that I want to collect data from, so I don't want to lose the data that has been collected already. I tried to google this, but all I can find is how to send data, not receive it. I also couldn't find how to do this beyond a binary "OK" or "cancel."
Does know how to do this?
The DialogResult portion simply allows you to determine if the User selected "OK" (or your equivalent of "OK"), or simply cancelled the dialog by clicking the "X" in the top right (in which case there might not be any valid "selections" in the dialog to retrieve).
If the User clicked "OK", then you can retrieve any desired values from the form reference that you already have. Conceptually, we are "pulling" from the main form, not "sending" from the child form. This is easier because the main form already has a reference to the child form (you used that reference to display the dialog!).
To do the opposite, and "send" from the dialog to the main, you'd have to pass a reference to the main form into the dialog form. There are cases where you'd want to do this, such as if you needed something to change in main, in real-time and possibly multiple times, before the dialog is closed by the user. Sometimes you need to only "pull", sometimes you need to "send", and sometimes you might need to do both. You'll have to decide which approach is best for your situation.
Assuming you only need to pull after the dialog is dismissed by the user, check the returned DialogResult, then use that form reference to retrieve the values:
Private Sub bttn_AW_SelectUnits_Click(sender As Object, e As EventArgs) Handles bttn_AW_SelectUnits.Click
'TODO: Capture output from next menu
Dim changeUnits As New AuditWizardUnits
If changeUnits.ShowDialog() = DialogResult.Ok Then
' Access something directly from a Control:
Dim value As String = changeUnits.TextBox1.Text
' ...or use a property that YOU created in changeUnits:
Dim values As List(Of String) = changeUnits.SelectedValues
End If
End Sub
In the dialog, you return "OK" when the user clicks on your OK/Save/Continue type button:
Private Sub btnOK_Click(...) Handles btnOK.Click
Me.DialogResult = DialogResult.Ok
End Sub
For the List aspect, you'd have to make that List accessible from outside the class so it can be retrieved like in my snippet above:
Public Class AuditWizardUnits
Public SelectedValues As New List(Of String)
End Class
You'd either populate that list before setting DialogResult, or populate it as the user interacts with the dialog.

VBA Hide User form but retain data entered into it

I'm back again with what I hope is a fairly easy question.
I'm attempting to create a user form in VBA. The user will enter certain bits of information into the form, and then close the form. I'd like the user form to retain the data entered after it is closed by the user. I'm treating it as a class module, since techinically they are, or at least that is how I understand it. Here is the code I'm using:
In the main sub that displays the user form:
Sub NonACATMemo()
Dim UserInput As MemoReasons
Set UserInput = New MemoReasons
UserInput.Show
... And then in the user form itself to close it...
Private Sub UserForm_Terminate()
MemoReasons.Hide
End Sub
I also call this sub from a command button on the form. The issue I'm running into is that when I use this method, I get an error "Run-time error '402': Must close or hide topmost modal form first." If I use unload me, when I try to get data out of the form it is cleared and I get a "server not available" error or something to that effect.
So, any ideas on hiding a user form but retaining the data inside?
Final couple of notes: This is the only user form in the project, and here is an example of how I'm trying to get data out of it using the Public Property Get method:
Debug.Print UserInput.EmailFlag
Debug.Print UserInput.ContraFirm
Debug.Print UserInput.MemoReason
Well, I'm all ears if anyone has any suggestions.
It's an old topic... hopefully someone will need a help on this.
You can do the following :
1-Place a Close/Cancel button (you can set Cancel property to True)
2-Attach following code to Click event
Private Sub btnClose_Click()
'Do some stuff if necessary
Me.Hide
End Sub
3-Attach this code to QueryClose event
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then 'vbFormControlMenu = 0 ([X] button on top right), see MSDN
Cancel = True 'Don't fire Terminate event...
btnClose_Click '...instead, call my close event handler
End If
End Sub
You can check the result by placing a debugger breakpoint in UserForm_Initialize event and it should be fired only for the first time showing the UserForm and thus, granting UserForm state preservation.
I've not seen this approach before. Normally, I would just instantiate the form by:
MemoReasons.Show
Indeed the _Terminate() event is wiping out the data held in the form. So the solution is to not call the _Terminate() event from the button-click. Instead, simply hide the form, e.g.:
Sub ShowMemoReasons()
'In a normal code module, this calls the form
' could be run from the macros menu or attached to
' a shape/button/etc on the worksheet.
MemoReasons.Show
End Sub
Put these in the MemoReasons code module:
Private Sub CommandButton1_Click() '<-- Rename to handle your button's click event
MemoReasons.Hide '## Hides the form but does not release it from memory
End Sub
Private Sub UserForm_Terminate()
'Any events pertaining to the termination of the form object
' otherwise, all form control data will be wiped out when
' this object releases from memory
End Sub
After you do these, if you use the button to HIDE the form, you can call the ShowMemoReasons() and it should re-display the form, while preserving data that was previously entered in the form.
If you use the red "X" button or some other event triggers the Terminate event, you will lose the form data. There are ways to do validation and prevent this with the QueryClose event if necessary.
Update
I don't think you need to Dim an instance of the user form (an exception would be if you will be potentially displaying multiple forms at the same time). Otherwise, declaring UserInput as a public variable is redundant and confusing.
Inicidentally, this is why you're getting the error: Must close or hide topmost modal form first. If you must implement it this way, instead of doing MemoReasons.hide you should use Me.Hide.
As long as you are only displaying one instance of the form, you can always refer to MemoReasons.property because MemoReasons is a public object, just like ThisWorkbook or ActiveWorksheet, etc.
Instead, you should be able to refer to this object (MemoReasons is an object) in any subroutine, for example create another one that is not called from the previous subs. Run the sub to show the form, enter in some data, and then hide the form. With the form hidden, then run this subroutine, and you should see the resulting data from the form.
Sub Test2()
Debug.Print MemoReasons.EmailFlag
End Sub

Access parent and other open forms from a subform

In continuation to my application development, I have encountered another intersting problem.
In my MS Access application, I am using a form which contains only two controls - a textbox and a command button. This form is named as HEADER FORM.
HEADER FORM is used as a subform in header section of various other forms.
Figure below shows the subform and its use in one of the main form.
Now, what I want is that when user clicks on Logout button of the subform, the logout action shall happen (which is fine and I am able to figure it out) and all the forms that are open at that point in time shall be closed / unloaded.
I tried using following code to no avail.
Option Compare Database
Private Sub cmdHeaderLogout_Click()
If (loggedIn = 1) Then
loggedIn = 0
DoCmd.Close acForm, Parent.Form
End If
End Sub
When I try to click on logout button, control reaches DoCmd.Close statement above. And execution stops after giving following error message:
Run-time error: 2498. An expression you entered is the wrong data type
for one of the arguments.
and it points to Parent.Form text.
I am not able to figure out how to refer to parent form and unload the same?
You should refer to the name of the parent of the current form, that is:
DoCmd.Close acForm, Me.Parent.Name
The second argument of DoCmd.Close takes a string.
You can also loop through the forms collection.
FormsCount = Forms.Count - 1
For i = FormsCount To 0 Step -1
If Forms(i).Name <> Me.Name Then
DoCmd.Close acForm, Forms(i).Name
End If
Next