I have a form Overview with a table that gets its data from a database. I would like to add a line to that database and update my table in Overview. I created a button in Overview which opens another form InputForm (that pops up in front of Overview). In VBA, I wrote some code that adds the data to the database using a query and then closes InputForm. When InputForm closes, Overview becomes visible again. Now, I would like to see the table in Overview updated with the new data. The problem is that it only updates when I click another button in Overview or when I close and reopen the form.
I tried the GotFocus, Activate, Click... events to Refresh the form but I guess that the form does not lose focus or is not deactivated when InputForm is opened so these events of course never happen. I also tried to Refresh Overview from within the InputForm. I also tried to find the Activate or Deactivate functions but they appear nowhere. I honestly don't know how to update the table in the Overview form.
EDIT:
Overview
Private Sub btnOpenInputForm_Click()
DoCmd.OpenForm FormName:="InputForm", OpenArgs:=0 & "," & 0
End Sub
InputForm
Private Sub btnAddRecord_Click()
'Read data from the input fields
'CurrentDb.Execute "INSERT..."
DoCmd.Close
End Sub
If I understand correctly, then your form named Overview is bound to the same table which will be a record added to by a button which also is on that form.
So the code to add the new record runs in the Click event of that button, right?
So then you would have to call Me.Requery after adding the record (The Me keyword is a reference to the form in that case).
Edit:
Regarding your new information I added this, showing how to call your InputForm as a modal dialog and read out the values in case the user didn't cancel it.
This would be your calling procedure:
Private Sub btnOpenInputForm_Click()
Const INPUT_FORM_NAME As String = "InputForm"
'Call the form as a modal dialog
DoCmd.OpenForm FormName:=INPUT_FORM_NAME, OpenArgs:=0 & "," & 0, WindowMode:=acDialog
'If the user cancelled the dialog, it is not loaded any more.
'So exit the sub (or maybe do some other stuff)
If Not CurrentProject.AllForms(INPUT_FORM_NAME).IsLoaded Then
Debug.Print "The user cancelled the dialog"
Exit Sub
End If
'You can now check a value in the dialog
If IsNull(Forms(INPUT_FORM_NAME).MyTextBox.Value) Then
Debug.Print "Null in the control"
Exit Sub
End If
'Or read a value into a variable
Dim myVariable As String
myVariable = Forms(INPUT_FORM_NAME).MyTextBox.Value
'Close the dialog form now
DoCmd.Close A_FORM, INPUT_FORM_NAME
'Build and execute your sql here, like you already did in the dialog form before
'CurrentDb.Execute "INSERT..."
Debug.Print "User entered: ", myVariable
'And finally requery the form
Me.Requery
End Sub
In the dialog form ("InputForm")
the Click procedure of the OK-button has to call Me.Visible = False to just hide the dialog.
the Click procedure of the Cancel-button has to call DoCmd.Close acForm, Me.Name to close the dialog.
Related
I have a form where users can edit multiple different pieces of data. This form is based on data pulled from several underlying tables and placed into a temporary table. When a user makes a change and hits the "save" button, any changes made in the form get updated/appended to the underlying data tables and everything in the temp table gets dumped. This all works great.
My problem is with the native close button on the form. If a user makes a change, forgets to hit save, and instead just closes the form, nothing gets saved. I think it's because I need to run my update and append queries (which is what happens with my save button) but I'm unsure how to incorporate them in so they run with the native close button. When I try to add them to the Form_Close event, I get an error message that something in the BeforeUpdate event is preventing Access from saving the data. I know I could remove the close button from the form, but if possible, I would rather leave it in.
Form_BeforeUpdate
txtOld = Nz(Me.Document.OldValue, "")
If Not (Me.NewRecord) Then
If MsgBox("Changes have been made to this record. Save changes?", vbYesNo, "") = vbNo Then
DoCmd.RunCommand acCmdUndo
End If
End If
cmdSave_Click
On Error GoTo Error_Handler
DoCmd.RunCommand acCmdSaveRecord
'check to see if new book field has changed and run append query if it has
If txtOld <> Me.Document.Value Then
DoCmd.OpenQuery "qryUpdateNewBookList"
End If
'This update query should run every time
DoCmd.OpenQuery "qryEditUpdate"
DoCmd.Close acForm, Me.Name, acSaveNo
Form_Close
DoCmd.RunSQL ("DELETE tblEditTbl.* FROM tblEditTbl")
One quick tips. You can use below code to through a message that data is not saved.
Private Sub cmdClose_Click()
If Me.Dirty = True Then
MsgBox "Data is not saved. Save data first then try to close", vbExclamation
Exit Sub
Else
MsgBox "Data saved successfully."
DoCmd.Close
End If
End Sub
Edit: If you want to check it before update then you have to use a variable to check if data is saved or not. Declare a variable at top of form code module like
Option Compare Database
Private blnSaveRecord As Boolean
Use below codes to Save button.
Private Sub cmdSave_Click()
blnSaveRecord = True
DoCmd.RunCommand acCmdSaveRecord
blnSaveRecord = False
End Sub
And finally write below codes to Form_BeforeUpdate event.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
If Not blnSaveRecord Then
Cancel = True
strMsg = "Please save the record.," & _
vbNewLine & "or press ESC from keyboard to cancel the operation."
MsgBox strMsg, vbInformation, "Save Record"
End If
End Sub
I solved my problem. Harun24HR got me thinking in the right direction. In addition to my existing code, I needed to use the Form_Unload event and create two public boolean variables to check if the save button had been clicked and if any edits had been made in the form.
Form_Unload
If Not SaveClicked And IsDirty Then
MsgBox "Data is not saved. Save data first and then try to close.", vbExclamation
Cancel = True
End If
I have a script that automatically generates a form. This form is only temporary and can be deleted after closing. To prevent having to do it manually, I'd like to add a button or a form_close() method in which there should be some code to delete the form (if this is possible at all).
Otherwise, I'd like to be able to prevent te pop-up forcing me to save the form and give it a name once I close it (shown below in Dutch).
I haven't been able to either disable this pop-up, or add VBA code using VBA code. Can anyone tell me wether this possible and maybe give an example?
You don't need VBA code in the form to do this, just call a public function from the OnClick event of the button.
' This is called from the "Close" button on the temp form
Public Function CloseWithoutSave(fName As String)
DoCmd.Close acForm, fName, acSaveNo
End Function
' Demo
Public Sub CreateTestForm()
Dim F As Form
Dim btn As CommandButton
Set F = Application.CreateForm()
F.Caption = "This is a test form!"
Set btn = CreateControl(F.Name, acCommandButton, Left:=100, Top:=100)
btn.Caption = "Close me"
btn.OnClick = "=CloseWithoutSave(""" & F.Name & """)"
' Open test form in form view
DoCmd.Restore
DoCmd.OpenForm F.Name, acNormal
End Sub
You can't add modules to forms without saving them, as far as I know, and forms need to be in design view to have a module added to them (just like when you add them through the GUI).
To start from your starting point (you have an open unsaved form):
Public Sub AddModuleToOpenUnsavedForm(strModuleText As String)
'Save the form name to a variable
Dim strFormName As String
strFormName = Screen.ActiveForm.Name
'Save and close the form
DoCmd.Save acForm, strFormName
DoCmd.Close acForm, strFormName, acSaveYes
'Open the form back up in desing view
DoCmd.OpenForm strFormName, acDesign
'Add a module to it
Forms(strFormName).HasModule = True
'Add code to the module
Forms(strFormName).module.InsertText strModuleText
'Close it again
DoCmd.Save acForm, strFormName
DoCmd.Close acForm, strFormName, acSaveYes
'Open the form back up again
DoCmd.OpenForm strFormName, acNormal
End Sub
Note that this does prompt a database-wide save. If you have any unsaved open objects, you will be prompted to save them.
Obviously, you can delete the form after using it, but you will have to do it actively instead of leaving it unsaved.
I'm using a VBA Userform. The MassPrompt userform has a set of six GroupNames and some text boxes. Each GroupName contains two or more radio buttons.
I'd like the following code to be triggered anytime any element within the GroupName "GROnly" changes. If the user made an inappropriate button choice in "GROnly" based on the choice in another group, I'd like to display a warning message and present the MassPrompt userform again.
Right now, I've assigned the code to the one button "GROnly_yes". It works, but only when that one button is clicked. How do I position this within the UserForm code to trigger anytime a button with the GroupName "GROnly" is clicked? Thanks for looking at this.
Private Sub GROnly_yes_Click()
'Prompt if the GROnly is true and it's inappropriate for the GSetting choice
If GROnly_yes = True And GSetting_renewal = True _
Then
GROnly_yes = False
GROnly_no = True
MsgBox ("The GROnly can't be chosen with a Renewal." & vbNewLine & _
"The GROnly button has been changed to 'NO'.")
UserForm_Initialize
End If
'Other IF statements here.
End Sub
If I understood well, GRonly is the GroupBox that contains (let's say) the radio_button_1 and radio_button_2.
The reason why the code doesn't trigger is that when he/she changes the value of one radio-button is not clicking on the GroupBox, but rather changing the value of that single radio-button.
You will have to add the code to the _Change event of the radio button objects. This is an example:
Sub myFunctionalCode()
'your code here
End Sub
Private Sub radio_button_1_Change()
myFunctionalCode
End Sub
Private Sub radio_button_2_Change()
myFunctionalCode
End Sub
Thanks for the reply. That would work.
In the meantime, I came up with another alternative as well. I removed the code from:
Private Sub GROnly_yes_Click()
And I moved it to the button that the user clicks to submit the form:
Private Sub ContinueButton_Click()
In my original code I had to change UserForm_Initialize to Exit Sub to make the code work in the "submit" button.
Thanks again for your help.
Phil
let me start by saying that i am new to access vba coding, so bear with me.
i open a form using dao code opened to a new record. however, i cannot seem to be able to save the record no matter what i try.
'opened a Form_MyForm for a new record.
dim frm as new form
set frm = new Form_MyForm
frm.recordset.addnew
frm.visible = true
On the "Form_MyForm" save button, i have the following code
private sub save_click()
me.dirty = (me.dirty = false)
docmd.close acForm, me.name
end sub
everything seems to work ok (including the ID, hwnd, etc) except that nothing gets saved on the table. if i use docmd.openform to open the form, then the code works...
First of all you create two forms, one of the type form, the other of the type of your form.
Anyway, I would recommend using the DoCmd.Openform command.
Normally you would not have to save any data. (On the contrary, if you want to not save the data you would use
If Me.Dirty = True Then
DoCmd.RunCommand acCmdUndo
Exit Sub
End If
If you need to access the form from vba after you opened it, use
Set frm = Application.Forms("My_Form")
And if you want to close the form programmatically again use DoCmd.close
I have form that adds records to a table. I have some VBA code on the AfterUpdate event of a combobox that changes the visibility of some of the other form controls depending on the value chosen.
I also have a save button, which runs this code when clicked:
Private Sub btnSave_Click()
On Error Resume Next
DoCmd.RunCommand acCmdSaveRecord
DoCmd.GoToRecord , "", acNewRec
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
End Sub
When I click the Save button, the controls that were made visible in the last record are still visible. I want to "Reset" all controls to their default visibility, so to speak.
Use a procedure for the form's On Current event. As you navigate to a different record, you can reset controls' visibility to your default choices. You can also set visibility conditionally ... so you might set visibility of a given control based on values of the current record.