Making class module from a form - forms

Is it possible to convert your form to a self contained class module in vb6?

One simple way to do this is to create a new ActiveX DLL project in the VB6 IDE, and then add a new Form to the project. You also need a class, but you can just rename the default "Class1" that gets added to the project.
Create the form as you normally would, and then write a class that has a function to display the form, and optionally return information back to the caller (either via a return value, events, or public properties on the class). Once you compile the DLL, other projects can use your form by adding a reference to your DLL and instantiating the public class.
Below is a very simple example that demonstrates how you might create a generic login dialog that you can then re-use in multiple projects. The login dialog simply displays a login screen with username and password fields, and OK and Cancel buttons. A public class, LoginDialog, can be used by other projects to actually display the login form and to retrieve data from it (the actual username and password entered by the user, and whether or not the user cancelled the dialog). The public class is a wrapper around the functionality provided by the form.
Please note this is just a quick example to demonstrate the concept
Create a new Form and add it to the ActiveX DLL project. Rename it frmLogin and add the following controls to it:
A Textbox named txtUsername
A Textbox named txtPassword. Set the PasswordChar property to "*" (asterisk)
A CommandButton named cmdOK with the caption set to "OK"
A CommandButton named cmdCancel with the caption set to "Cancel"
Then add the following code to frmLogin.frm:
'frmLogin.frm'
Public Cancelled As Boolean 'Set if the user clicks Cancel or closes the form'
Private Sub cmdCancel_Click()
'User cancelled the dialog by clicking Cancel...'
Me.Cancelled = True
Me.Hide
End Sub
Private Sub Form_QueryUnload(Cancel As Integer)
'User cancelled the dialog by closing the window...'
Me.Cancelled = True
Me.Hide
End Sub
Private Sub cmdOK_Click()
'Make sure the user filled in both fields.'
If Trim(txtUsername.Text) = "" And _
Trim(txtPassword.Text) = "" Then
MsgBox "You must enter both a username and password."
Exit Sub
ElseIf Trim(txtUsername.Text) = "" Then
MsgBox "You must enter a username."
Exit Sub
ElseIf Trim(txtPassword.Text) = "" Then
MsgBox "You must enter a password."
Exit Sub
End If
'User filled in the necessary data - we can hide the form now'
Me.Cancelled = False
Me.Hide
End Sub
Rename "Class1" in the project to "LoginDialog" and add the following code. This is the class other projects will use to diplay the login form (frmLogin):
'LoginDialog.cls'
'A public class that allows other projects to display a login '
'dialog and retrieve the user`s login information and whether or not '
'they cancelled the dialog. '
'This code assumes you have a form in the same project named frmLogin'
'and that it contains 2 textboxes, txtUsername and txtPassword, and '
'2 command buttons, cmdOK and cmdCancel. '
' '
Public Username As String 'The username entered by the user'
Public Password As String 'The password entered by the user'
Public CancelledByUser As Boolean 'True if the user cancels or closes the form'
'Shows a new Login form with the specified defaults filled in, if provided.'
' '
' '
Public Function Show()
'Create the login form and fill in the defaults'
Dim frm As frmLogin
Set frm = New frmLogin
frm.txtUsername = Me.Username
frm.txtPassword = Me.Password
'Shows the form until it is hidden or closed'
frm.Show vbModal
If frm.Cancelled Then
Me.CancelledByUser = True
Else
'Get the username and password from the form'
Me.Username = frm.txtUsername
Me.Password = frm.txtPassword
Me.CancelledByUser = False
End If
'Unload the form'
Unload frm
End Function
Compile the ActiveX project and give it a name (i.e. MyAppLoginUI) so you can easily identify it when you need to add it to other projects.
When you want to use the form in another project, go to Project -> References... in the menu, and add your ActiveX DLL to the project. You may have to click Browse... to find it. Below is an example of how other code might use the example login dialog we just created:
'LoginExample.bas'
' A simple example of how another project might use '
' the generic login form created in the previous steps. '
' This example displays the login screen, then tries '
' to authenticate the user against a database. '
' '
Public Sub PerformLogin()
Dim login As New LoginDialog
'Pre-fill the username with the username of the last user who logged in.'
login.Username = GetSetting("MyApp", "Settings", "LastUser")
'Show the login screen. It will stay up until the user clicks OK or Cancel'
login.Show()
'If the user cancelled the login form, exit now...'
If login.CancelledByUser Then
Exit Sub
End If
'Pretend DAL is a data access layer module...'
If Not DAL.LoginUser(login.Username, login.Password)
MsgBox "Invalid username or password.", vbCritical+vbOKOnly, "Login Failure"
End If
End Sub

Related

Ms Access - Button with code doesn't work to send email

I have this code set in access, but no email is sending upon clicking the button on the form. I have outlook open. When i click the button on the form, i can't see anything that actually happens. I want the email address to be equal to the value in [text1], and I am trying to make the subject include a fixed message plus the input from [text2]. Even without these variables, I can't get this to work
Public Sub Command495_Click()
Dim mailto As String
Dim ccto As String
Dim bccto As String
mailto = [text1]
ccto = ""
bccto = ""
emailmsg = "trial"
mailsub = [text2] & ", Does this work?"
On Error Resume Next
DoCmd.SendObject acSendNoObjectType, , acFormattxt, mailto, ccto, bccto, mailsubj, emailmsg, True
End Sub
I have checked to make sure the onclick property shows event procedure. I am stuck, please help!
Here are a few suggestions and a modified version of your code.
ALWAYS use Option Explicit and compile your module before testing. You had a number of variables that were not defined and incorrect spelling of some options.
NEVER bypass errors when testing (get rid of your "On Error Resume Next") That's why you never saw an error.
Look for every place I entered ">>>" and address that issue.
Always explicitly define your variables and use the proper Type. Removes all doubt of what/where something is.
Option Compare Database
Option Explicit
Public Sub Command495_Click()
Dim mailto As String
Dim ccto As String
Dim bccto As String
Dim emailmsg As String
Dim mailsub As String
mailto = [Text1] ' >>> Where is [Text1]?? Remove for testing
ccto = ""
bccto = ""
emailmsg = "trial"
mailsub = [Text2] & ", Does this work?" ' >>> Where is [Text2]?? Remove for testing
' >>> Bad idea to ignore errors when testing!!
On Error Resume Next
'>>> Following line had: (1) 'acSendNoObjectType' which is incorrect; (2) mailsubj, which is undefined
DoCmd.SendObject acSendNoObject, , acFormatTXT, mailto, ccto, bccto, mailsub, emailmsg, True
End Sub

VBA Access form: Submit Button to create new record but keep some values in the form

I have a form to enter all necessary data. With the wizard I created a button that saves the data as a new record, but this button clears the form.
I want this button to do exactly that, but keep some of the entered values in the form, because those values will stay the same for a certain amount of records.
Currently my button runs this code generated by the button creation wizard:
Private Sub submit_btn_Click()
On Error GoTo submit_btn_Click_Err
On Error Resume Next
DoCmd.GoToRecord , "", acNewRec
If (MacroError <> 0) Then
Beep
MsgBox MacroError.Description, vbOKOnly, ""
End If
submit_btn_Click_Exit:
Exit Sub
submit_btn_Click_Err:
MsgBox Error$
Resume submit_btn_Click_Exit
End Sub
When the button is clicked I want to clear all values in the form, except for the date and a group field. Can I easily do this in this code or is there a way to do this via the default value property of these fields?
Try the following:
Go to the properties of your form and put the following code in the BeforeUpdate event:
Private Sub Form_BeforeUpdate(Cancel As Integer)
entry_date.Tag = CLng(entry_date.Value)
acc_value.Tag = acc_value.Value
End Sub
In the Current event of the form, put the following code:
Private Sub Form_Current()
If Me.NewRecord Then
entry_date = CDate(entry_date.Tag)
acc_value = acc_value.Tag
End If
End Sub
That is all you need to do. If you have any questions please let me know

Form Gathering Info from Two Other Forms

I have a form that creates a New Work Order. I want to be able to pull the ClientID from the New Client Form or the Main Menu, whichever is open. However I am not getting the desired results:
I have used =IIf(IsNull(Forms![New Client]![txtClientID]), Forms![Main Menu]![txtClientID], Forms![New Client]![txtClientID]) in the Default Value of the Control on the New Work Order Form. I get the correct ID when I go to the form from New Client, but a #Name error when I try to access it from the Main Menu.
What can I do to make it work?
You need to check if the form is loaded, for example (you need to add your own error traps):
Function IsLoaded(ByVal strFormName As String) As Boolean
Const conObjStateClosed = 0
Const conDesignView = 0
If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
If Forms(strFormName).CurrentView <> conDesignView Then
IsLoaded = True
End If
End If
However, it may be easier to use OpenArgs ( http://msdn.microsoft.com/en-us/library/office/ff820845(v=office.15).aspx )
In which case you could say something like:
If IsNull(Me.OpenArgs) Then
MsgBox "No openargs"
Else
Me.txtClientID = Me.Openargs
End If
Or even use Openargs to set the default value.

form_load subroutine in MS Access VBA

I am writing a code in MS Access VBA, which is as follows:
Private Sub Form_Load()
MsgBox "loggedIn = " + CStr(loggedIn)
If (loggedIn = 1) Then
Else
Exit Sub
End If
End Sub
I want to decide whether to load the form or not based on loggedIn variable. If loggedIn variable is 1, form shall be loaded. If the same is not 1, form shall not be loaded.
Issue that I am facing is that, whatever I do in ELSE part of the code above, I am not able to stop the form from loading.
How can I achieve this?
Pls comment if any additional information is required.
Thank you.
If the loggedIn value is available at form open, you could cancel the form open event.
Private Sub Form_Open(Cancel As Integer)
Cancel = Not (loggedIn = 1)
End Sub
If the value of loggedIn is not available until the form's load event, you can close the form.
Private Sub Form_Load()
If loggedIn <> 1 Then
DoCmd.Close acForm, Me.Name
End If
End Sub

How to open another Form from current Form?

Our first form is the LOG IN form..how can I open to the next form after logging in?
In your log-in form, I assume you perform your validation inside of the Click event method for a button control. So you would have something like:
Private Sub btnLogin_Click()
If ValidatePassword(txtPassword.Text) Then
' The password is correct, so show the main form and close the login form
MainForm.Show
Unload Me
Else
' The password is incorrect, so leave this form on screen
MsgBox "Invalid password entered!", vbError
txtPassword.SetFocus
End If
End Sub
The two interesting features of this code are:
The Show method, which you call on the form object that you want to show.
In this case, it will probably be your main form—replace MainForm with whatever it is called.
The Unload statement, which closes and destroys the specified form.
In this case, Me refers to the login form since you're finished with it.
You will need call Show on the form which needs to be displayed post login form. You can read more about Understanding Forms and form events
My approach is to avoid trying to open a logon Form as the first Form.
Instead let the main Form be first, and in its Load event Show your logon Form as a modal dialog. This can be done revealing the main Form first by doing a Show on it. Example based on the standard template "Log in Dialog" Form with some code changes:
frmMain.frm
Option Explicit
Private Sub Form_Load()
Dim Control As Control
Show
frmLogin.Show vbModal, Me
With frmLogin
txtSuccess.Text = CStr(.LoginSucceeded)
If .LoginSucceeded Then
'Proceed normally, perhaps after capturing
'the User Name, etc.
txtUserName.Text = .User
txtPassword.Text = .Password
Else
'Do "Unload Me" or disable all controls
'as shown here, etc.
For Each Control In Controls
On Error Resume Next
Control.Enabled = False
On Error GoTo 0
Next
End If
End With
Unload frmLogin
End Sub
frmLogin.frm
Option Explicit
Public LoginSucceeded As Boolean
Public User As String
Public Password As String
Private Sub cmdCancel_Click()
LoginSucceeded = False
Hide
End Sub
Private Sub cmdOK_Click()
'Check for correct password, hard-coded here.
If txtPassword.Text = "password" Then
LoginSucceeded = True
User = txtUserName.Text
Password = txtPassword.Text
Hide
Else
MsgBox "Invalid Password, try again!", , "Login"
With txtPassword
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End With
End If
End Sub