Is there any way to change the properties of a Ms Access dialog Form when is Opened? - vba

Instead of using msgBox, I want to create My msgBox by form, "frmMsg".
"frmMsg" form has tow bottom, (Ok and No), and a label(lblMsg) for show message.
"frmMsg" property: Pop Up = Yes , Modal = Yes.
My Function for Open form is MsgInfo:
Public Function MsgInfo(Optional msg As String = "Are You Ok?", _
Optional msgCaption As String = "Warning" ) As Boolean
MsgInfo = False
DoCmd.OpenForm "frmMsg"
Form_frmMsg.Caption = msgCaption ' Set Caption of Form
Form_frmMsg.lblMsg.Caption = msg ' Set Message of Form
MsgInfo = MsgInfoResult ' MsgInfoResult is Public Variable to store MsgInfo Result (Ok Bottom(True) or No Bottom(False) )
End Function
I used this in other Form, Example For delete Customer in Customer List ( Delete Bottom ):
Private Sub btnDelete_Click()
DoCmd.SetWarnings False
If MsgInfo("Are You Sure Delete Customer?", , "Delete Customer!") = True Then
' Run SQL for Delete Customer
Dim sqlDelete As String
sqlDelete = "DELETE tblCustomer.*, tblCustomer.RowId " & _
"FROM tblCustomer " & _
"WHERE tblCustomer.RowId=[Forms]![frmCustomerList]![frmCustomerListSub]![RowId]"
DoCmd.RunSQL sqlDelete
Form_frmCustomerList.frmCustomerListSub.Requery
End If
DoCmd.SetWarnings True
End Sub
My Problem is After Open MsgInfo Form Before the user answers this, the Next commands (Sql) are executed.
To solve the problem, I changed AcWindowsMode in Function MsgInfo:
DoCmd.OpenForm "frmMsg"
to
DoCmd.OpenForm "frmMsg", , , , , acDialog
problem solved but There was another problem. The following commands are not executed:
Form_frmMsg.Caption = msgCaption ' Set Caption of Form
Form_frmMsg.lblMsg.Caption = msg ' Set Message of Form
MsgInfo = MsgInfoResult ' MsgInfoResult is Public Variable
please help me.

I am no Expert in VBA or Any Programming Language neither am I a programmer by Profession. But , I've had my fair share in dealing with programming languages as a hobby.
In VBA, Any Code after the ,,,,,acDialog can't be run until the Form is closed so , What you need to do is find a way to Pass the Messages somewhere and have the form Retrieve it.
Create a Module to Pass the Message from the Function to the Form
'a Module named Module_gVar
Public MessageHeader as String 'Optional A Separate Text Box For a Header
Public MessageBody as String 'Main Body
Public MessageTitle as String 'Caption of the Form
Public MessageReturn as Boolean
This is the function to Call the Message box and Get a simple True or False Return
'Function To Call the MessageBox
Public Function CallMessageBox ( _
Optional msgHeader as string , _
Optional msgBody as string , _
Optional msgTitle as string)
Module_gVar.MessageTitle = msgTitle
Module_gVar.MessageHeader = msgHeader
Module_gVar.MessageBody = msgBody
DoCmd.OpenForm "frmMessage",,,,,acDialog
CallMessageBox = Module_gVar.MessageReturn
'You can have the CleanUp on a Separate Function
'Since it's not a Procedure Variable it Isn't cleaned when it goes out of scope
Module_gVar.MessageTitle = ""
Module_gVar.MessageBody = ""
Module_gVar.MessageHeader = ""
Module_gVar.Return = False
End Function
Now for the Form itself.
'Retrieve the Strings
Private Sub Form_Current()
Me.[YourHeaderTextBox] = Module_gVar.MessageHeader
Me.[YourBodyTextBox] = Module_gVar.MessageBody
Me.Caption = Module_gVar.MessageTitle
End Sub
'A Button to Return a Value
Private Sub cmdYes_Click() ' Yes button
Module_gVar.MessageReturn = True
DoCmd.Close acForm,"frmMessage",acSaveNo
End Sub
Private Sub cmdNo_Click() ' No Button
Module_gVar.MessageReturn = False
Docmd.Close acForm,"frmMessage",acSaveNo
End Sub
You can Optimize the code from here on but it's the basic structure. I Recommend creating a Class Module in which you can retrieve strings , input strings , and call Forms.

Related

prevent duplicates when passing values between two forms (with Args)

I have two forms: transfert Form with its subform and intransfert Form. I am using
DoCmd.OpenForm "intransfert", , , , acFormAdd, acDialog, Me!Text83
(where text83 is =[transfertasubform].[Form]![transfertadetailid] under
Private Sub Command78_Click()
in transfet form and
Private Sub Form_Load()
On Error Resume Next
If Me.NewRecord Then Me!trnrin = Me.OpenArgs
in intransfet form. intransfert form is based in transfertdetailquery. i wont to prevent passing text83 value more then one time
i tried to explain my problem and expect a help to prevent duplicates when used Arge
assuming trnrin is the name of a variable in your record source. assuming you mean that you want to avoid adding two records where trnrin has the same value and the user sent the same open args twice. assuming trnrin is also the name of a control in the detail section of the intransfert form.
'form load only runs when the form is opened so you have to close the form to pass new args
'but you can just move the same code to a button or whatever
Private Sub IntransferForm_Load()
If Len(Me.OpenArgs) > 0 Then
Me.txtBoxintheHeader = Me.OpenArgs 'the load event is the right place to set controls
'most of this code is to check if there is already an instance where trnrin = the OpenArgs in the record source
Dim lookedupArgs As String
lookedupArgs = Nz(lookedupArgs = DLookup("trnrin", "MyTable", "trnrin = " & "'" & Me.OpenArgs & "'"), "ValuethatisneveranArg")
If lookedupArgs = "ValuethatisneveranArg" Then
'Debug.Print "trnrin = '" & Me.OpenArgs & "'" 'note the string delimiters
'Me.trnrin = Me.OpenArgs 'this surprisingly works but will break easily and doesn't handle complex cases
Dim rs As Recordset
Set rs = Me.Recordset 'if recordset is bound to a table then table will also be updated.
'you can also bind to the table directly but you may need to call me.requery to show the changes
rs.AddNew
rs!trnrin = Me.OpenArgs
rs.Update
End If
End If
End Sub

popup message shown while form closing

I have a database with the following
Mainfrm Form (Main Form - it has popup messages on load event)
kikThemOut Form (Loads hidden with Main Form and every 5 sec it checks for field value on table if it is 1 then call the Function fGetOut())
GetOutMod Module (has fGetOut() Function)
it works all fine, except when application closing it loads the popup alerts from Mainfrm again! which should not load.
Mainfrm Form Code
Private Sub Form_Load()
'to check for T&I notifications
Dim trs As Recordset
Set trs = CurrentDb.OpenRecordset("Y22_CurrMonth")
If trs.EOF = False Then
Dim tMsg, tStyle, tTitle, tHelp, tCtxt, tResponse, tMyString
tMsg = "There are Notifications Due, Do you want to view them?"
tStyle = vbYesNo + vbExclamation + vbDefaultButton2
tTitle = "Notifications Alert"
tHelp = "DEMO.HLP"
tCtxt = 1000
tResponse = MsgBox(tMsg, tStyle, tTitle, tHelp, tCtxt)
If tResponse = vbYes Then ' User chose Yes.
DoCmd.OpenReport "Notifications Current Month", acViewReport, acWindowNormal
Else
tMyString = "No"
End If
End If
'to load the checker form
DoCmd.OpenForm "kikThemOut", , , , , acHidden
End Sub
and this is the GetOutMod Module to force users to exit the db
GetOutMod Module
Option Compare Database
Option Explicit
Function fGetOut() As Integer
Dim RetVal As Integer
Dim db As DAO.Database
Dim rst As Recordset
On Error GoTo Err_fGGO
Set db = DBEngine.Workspaces(0).Databases(0)
Set rst = db.OpenRecordset("KickEmOff", dbOpenSnapshot)
If rst.EOF And rst.BOF Then
RetVal = True
GoTo Exit_fGGO
Else
If DSum("GetOut", "KickEmOff") = "1" Then
Application.Quit
Else
RetVal = True
End If
End If
Exit_fGGO:
fGetOut = RetVal
Exit Function
Err_fGGO:
'Note lack of message box on error
Resume Next
End Function
And this code in the load event of kikThemOut form to check for the same condition, if it is 1 then load this popup message (I could not add popup message to my GetOutMod Module with the function fGetOut)
kikThemOut form Code
Private Sub Form_Timer()
If DSum("GetOut", "KickEmOff") = "1" Then
Set TaskDialogAC = New cTaskDialog
With TaskDialogAC
.Init
.MainInstruction = "Dashboard Maintenance"
.Flags = TDF_CALLBACK_TIMER
.Content = "The Dashboard will be closed after 20 seconds for maintenance"
.CommonButtons = TDCBF_CLOSE_BUTTON
.IconMain = IDI_WINLOGO
.Footer = "Closing in 20 seconds..."
.Title = "Dashboard Maintenance"
.AutocloseTime = 20 'seconds
.ParenthWnd = Me.hwnd
.ShowDialog
End With
Call fGetOut
Else
If DSum("GetOut", "KickEmOff") = "0" Then
DoCmd.Requery
End If
End If
End Sub
Really hard to read your code and figure out where your function is being called from.
But I'm assuming this should work for you as described
Add this before your fGetOut function
Public blClosing as Boolean
And then add this inside your function at the top (after On Error GoTo Err_fGGO)
if blClosing then
blClosing = False
Exit function
Else
blClosing = True
End if

Access modal form updates database then calling form update does not

In Access a header form needs an address associated with it. The header form calls a modal address form. On Save the modal address form will write the address ID to the header form's record source address ID then close. Coming back to the calling header form should then list the related address ID after a requery, that is the FK link. I am not getting the address form's address ID written to the header form's record source address ID field and thus not listing on requery. A fair amount of this code is based on several SO questions.
The header form calls a wrapper function to manage the modal address form:
Private Sub txtJob_AfterUpdate()
gbolDropShipAddressCompleted = False
'Use global variables for use in frmDropShipAddress SQL update statement
gtxtCurrentJobNumber = Me.Job
gtxtCurrentJobRelease = Me.REL
gtxtCurrentJob = Me.txtJob
'Call the wrapper function
gbolDropShipAddressCompleted = fNewDropShipAddressCompletion()
If gbolDropShipAddressCompleted = True Then
'Me.Dirty = False
Me.Requery
With Me.RecordsetClone
.FindFirst "[Job] = '" & gtxtCurrentJobNumber & "' And [REL] = '" & gtxtCurrentJobRelease & "'"
If Not .NoMatch Then
If Me.Dirty Then
Me.Dirty = False
End If
Me.Bookmark = .Bookmark
End If
End With
'Reset all variables
gbolDropShipAddressCompleted = False
gtxtCurrentJobNumber = ""
gtxtCurrentJobRelease = ""
gtxtCurrentJob = ""
End If
End Sub
The wrapper function:
Public Function fNewDropShipAddressCompletion() As Boolean
'Manages call to frmDropShipAddress
DoCmd.OpenForm "frmDropShipAddress", , , , , acDialog, "From frmPackingSlipHeader"
fNewDropShipAddressCompletion = gbolfrmDropShipAddressTofrmPackingSlipHeader
DoCmd.Close acForm, "frmDropShipAddress"
End Function
The modal form's two events:
Private Sub btnSaveAddressInfo_Click()
DoCmd.RefreshRecord
'Update MAIN table with new address id using global variables
CurrentDb.Execute " UPDATE [MAIN] " & _
" SET intADDRESS_ID = " & Me.txtAddress_ID & _
" WHERE JOB = '" & gtxtCurrentJobNumber & "'" & _
" AND REL = '" & gtxtCurrentJobRelease & "'"
gbolfrmDropShipAddressTofrmPackingSlipHeader = True
Me.Visible = False
End Sub
Private Sub Form_Open(Cancel As Integer)
gbolfrmDropShipAddressTofrmPackingSlipHeader = 0
If Me.OpenArgs = "From frmPackingSlipHeader" Then
DoCmd.GoToRecord , , acNewRec
'Coded because TabCtlDatePicker opens all forms and openargs is NULL and causes all forms to be affected
ElseIf IsNull(Me.OpenArgs) Then
Exit Sub
' Else
' Me.PopUp = True
' Me.Modal = True
' Me.BorderStyle = 1
' Me.NavigationButtons = False
' Me.RecordSelectors = False
End If
End Sub
The Access front-end uses several tab controls to select between many different reports/date and or data pickers all sorted into tab control pages by topic. The back-end is MS SQL server via linked tables. The address form may be opened for generic viewing or called (modal). I can't seem to get the correct VBA to get the address form's address ID written to the header's record source and the VBA to get the header to requery and return to the correct record. Any help would be appreciated and TIA.
Tim

Is it possible to create an 'input box' in VBA that can take a text selection with multiple lines as an input?

I am trying to create a macro that will filter out relevant information from some selected text (smaller than a page long). This information will then be used to fill out a MS-Word template.
I have been opening the selected texts via a .txt file however I feel it will improve workflow if it were possible to copy & paste the selected text into some form of an input box.
I have tried the following:
Dim text As String
text = InputBox("Enter selected text here:")
This however only accepts a string (a single line of text).
Thanks, Donfernanado
As Rich Holton pointed out, you can create your own InputBox that supports the desired functionality:
First create a UserForm which looks like an InputBox. Mine is called CustomInputBox.
Set the MultiLine Property of the TextBox to True.
Example:
Then add some logic for the buttons and a Function to Show your Inputbox which takes some parameters like Prompt and Title:
Option Explicit
Private inputValue As String
Private Cancel As Boolean
Private Sub btnCancel_Click()
Cancel = True
Me.Hide
End Sub
Private Sub btnOK_Click()
If Me.txtInput.Value <> "" Then
inputValue = Me.txtInput.Value
End If
Me.Hide
End Sub
'This is the Function you are going to use to open your InputBox
Public Function Display(Prompt As String, Optional Title As String = "", Optional Default As String = "") As String
Cancel = False
Me.lblPrompt.Caption = Prompt
If Title <> "" Then
Me.Caption = Title
Else
Me.Caption = "Microsoft Excel"
End If
If Default <> "" Then
Me.txtInput.Value = Default
Else
Me.txtInput.Value = ""
End If
Me.txtInput.SetFocus
Me.Show vbModal
If Not Cancel Then
Display = inputValue
Else
Display = ""
End If
End Function
Now you are able to use your InputBox like this:
Dim text As String
text = CustomInputBox.Display("Enter selected text here:")

"Invalid use of null" for OpenArgs when calling OpenForm

I cannot find the reason but I keep getting an invalid use of null when using OpenArgs
The code is set up with
Private Sub cmdContactDetails_Click()
Dim ArgsString As String
ArgsString = Forms!LeadList![Entrepreneur Name] & "," & Forms!LeadList![Telephone Number] & "," & Forms!LeadList![Email Address]
DoCmd.OpenForm "ContactDetails", , , , , , ArgsString
End Sub
This results in the string "X,123456789,test#test"
In the Form_Open event of contact details I have:
Dim SaveString As String
SaveString = Forms!ContactDetails.OpenArgs
But this gives me an "Invalid Use of Null" message even though nothing is null.
Assuming you have a form named:- "LeadList"
and the form also has a text box named:- "Entrepreneur_Name"
and this form contains the following code:-
Option Compare Database
Option Explicit
Private Sub cmdContactDetails_Click()
Dim ArgsString As String
ArgsString = Me.Entrepreneur_Name
DoCmd.OpenForm "ContactDetails", , , , , , ArgsString
End Sub
The above code is called via a command button named "cmdContactDetails" on the form named:- "LeadList" then the form "ContactDetails" will be opened (form "ContactDetails" must be closed first) and the on open event will run this code:-
Option Compare Database
Option Explicit
Private Sub Form_Open(Cancel As Integer)
Dim SaveString As String
SaveString = Forms!ContactDetails.OpenArgs
MsgBox " >>> " & SaveString
End Sub
The message box will display the contents of the text transferred via the open args function from the form "LeadList" text box "Entrepreneur_Name"