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.
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 am working with Access Database VBA.
I have noticed if a user has filled a few of the text boxes in and then clicks the windows close button, the form logs that into the records.
I am wondering what is the best way to prevent the form from entering the uncompleted record on close?
There were a few sites pointing to placing a code in the beforeupdate function.
This is what I have tried.
Private Sub frmRecLog_BeforeUpdate(Cancel As Integer)
DoCmd.SetWarnings False
Me.Undo
Cancel = True
Exit Sub
End Sub
This code does not work at all for me.. I tried my best, haha.
Anything helps.
So, what you need is to insert a command button Save. If user do not hit on Save then it will not save any records. They will get a warning that data is not saved. You need declare a private boolean variable and write codes to save and warning. So full code will be like below.
Option Compare Database
Option Explicit
Private blnSaveRecord As Boolean
Private Sub cmdSave_Click()
blnSaveRecord = True
DoCmd.RunCommand (acCmdSaveRecord)
blnSaveRecord = False
End Sub
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."
Call MsgBox(strMsg, vbInformation, "Save Record")
'Me.Undo 'You can set undo option here if you do not want to press ESC.
End If
End Sub
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.
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 know this is probably a stupid question, but you know what they say. I have VBA in an Access Database with commands for On Click. Essentially it is a form with a combo box and timestamp for user login. Once the button is clicked a data entry form will load dependent upon which name is selected from the Combo Box. I would like for the Login Form to close once the data entry form has opened. The problem is that no matter where I put the DoCmd.Close the stupid form won't CLOSE!
In case it matters this form is set to open automatically when a user opens the database.
Below is the VBA for the Event Procedure associated with the button.
Option Compare Database
Private Sub TimeInButton_Click()
Dim strLoginForm As String
If Me.AgentCombo = "Amber" Then
strForm = "frmCustomersAmber"
ElseIf Me.AgentCombo = "Amanda" Then
strForm = "frmCustomersAmanda"
ElseIf Me.AgentCombo = "Brett" Then
strForm = "frmCustomersBrett"
ElseIf Me.AgentCombo = "Marcus" Then
strForm = "frmCustomersMarcus"
ElseIf Me.AgentCombo = "Terrah" Then
strForm = "frmCustomersTerrah"
End If
'------------------------------------------------------------
' TimeInButton_Click
'
'------------------------------------------------------------
On Error GoTo TimeInButton_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
DoCmd.OpenForm strForm
TimeInButton_Click_Exit:
Exit Sub
TimeInButton_Click_Err:
MsgBox Error$
Resume TimeInButton_Click_Exit
End Sub
DoCmd.Close takes optional arguments that will make it much more reliable. For example,
DoCmd.Close acForm, "MyFormName"