in MS ACCESS, is it possible to do: DoCmd.OpenForm "Dlookup...."? - ms-access

MS Access 2013
I have a tblUser table with following data (UserName / Password / StartForm)
I have a login system in place where user puts in form field called txtLogin his UserName.
After UserName and Password matches, I need to open a specific form for each user (depending on his function in the company).
I have this code in place but can't figure out the problem.
DoCmd.OpenForm DLookup("StartForm", "tblUser","[UserName]='" & txtLogin & "';")
I am only starting programming and I want to learn, not copy/paste code, so I appreciate very much if you can give me a simple explanation.
Thank you

The first parameter to DoCmd.OpenForm is the form name. To open the form to a specific parameter you need to use the
4th parameter which is the WhereCondition.
The Dlookup function is not necessary here. It is used to return a single column from a single record where the sourced column is the first parameter and the source table is the second parameter. It knows what record to grab by the search criteria, the third parameter.
The way you have this set up you are asking DoCmd.OpenForm to open a form by the name of [the result of your DLookup call] with no filter applied.
What you want is more like this
DoCmd.OpenForm NameOfYourUserForm, acNormal, , "[UserName]='" & txtLogin & "'"

I was able to solve the problem as following.
I created a variable for the form I want to call (nomeForm) and I used Dlookup to find appropriate form to each user.
Thank you
Private Sub cmdLogin_Click()
Dim rst As Recordset
Dim nomeUsuario As String
If IsNull(txtLogin) Or IsNull(txtSenha) Then
MsgBox "Preencha o login e senha"
Exit Sub
End If
nomeUsuario = txtLogin
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tblUser WHERE UserName = '" & txtLogin & "' AND Password = '" & txtSenha & "';")
If rst.RecordCount = 1 Then
bcansafelyclose = True
DoCmd.Close
Dim nomeForm As String
nomeForm = DLookup("Start", "tblUser", "UserName = '" & nomeUsuario & "'")
DoCmd.OpenForm nomeForm
Else
MsgBox "Login ou senha incorretos"
bcansafelyclose = False
End If
rst.Close
End Sub

Related

How to record unbound control to a database

I have a form control (address) that uses Dlookup to call info from a table "database" but the form is bound to table "Tracker". The dlookup is based on another control on the same form - "Name" I need the form to record this dlookup control, along with other controls that are bound to "tracker" as new recordto the table "tracker."
My failed attempts:
Using the default value property to assign the recalled data from the dlookup to another text box which would be bound to "tracker" This simply does not work for some reason. Perhaps I am missing something that tells this control "Address" to update upon selecting the correct "name?"
Code:
Private Sub SubmitReferral_Click()
On Error GoTo Err_SubmitReferral_Click
DoCmd.GoToRecord , , acNewRec
Exit_SubmitReferral_Click:
Exit Sub
Err_SubmitReferral_Click:
MsgBox Err.Description
Resume Exit_SubmitReferral_Click
End Sub
I also tried this - to assign the data - but the data from the dlookup in control "Address1" is not transferring/copying to control "Address2"
Private Sub Combo276_OnUpdate()
OnUpdate ([Address2].Value = [Address1].Value)
End Sub
Help or suggestions?
PS - I have tried to Edit per request to be as specific as possible, and to follow proper board etiquette.
Still unsure of your field names, etc., but the following is an example you can modify. Change 'tblEmployee' to 'database'.
I must state that if you are just starting out with developing in Access (or VBA) that you should never use names that are reserved words, or that can be misleading. Your table named 'database' is ok if named 'tblDatabase'.
Option Compare Database
option Explicit
Private Sub cmdInsert_Click()
Dim strSQL As String
Dim i As Integer
Debug.Print "cmdInsert; "
i = MsgBox("Do you want to add 1 row for Employee ID: " & Me.EmpID & " to table 'tracker'?", vbYesNo, "Confirm Add")
If i = vbNo Then
Exit Sub
End If
DoCmd.SetWarnings True
strSQL = "INSERT INTO tracker ( FirstName, LastName, Add1, City, St, Zip ) " & _
"SELECT tblEmployee.FirstName, tblEmployee.LastName, tblEmployee.Add1, tblEmployee.City, tblEmployee.St, tblEmployee.Zip " & _
"FROM tblEmployee " & _
"WHERE (((tblEmployee.EmpID)=" & Me.EmpID & "));"
DoCmd.RunSQL strSQL
End Sub
Thanks for the help - I solved my concern by hiding the fields that contain the dlookup, and putting code behind a button that copies the information to fields that are bound and therefore will record to the table "tracker"

Warning for Dynamic Combobox list

I have a combobox that builds it's list upon first usage. I know that the way I want "NotInList" to behave isn't conventional - I don't want to waste adding the item to a table separate from the needed entry, but I'd like to still warn about an item that hasn't been used yet, so that the user has to think twice before accepting the entry.
Once the user adds the item, it will automatically appear in the list next time because the data source for the combo box is as follows:
SELECT tbl_SP.PROGRAM
FROM tbl_SP
GROUP BY tbl_SP.PROGRAM
HAVING (((tbl_SP.PROGRAM) Is Not Null And (tbl_SP.PROGRAM)<>""));
I tried this:
Private Sub cmbPROGRAM_NotInList(NewData As String, Response As Integer)
If MsgBox("'" & Chr(34) & NewData & Chr(34) & " hasn't been used yet. Add to list? ", vbQuestion + vbYesNo, "Add - " & NewData & "?") = vbYes Then
Response = acDataErrAdded
End If
End Sub
but of course, Access wants the item to actually exist before it will release the error. And...if I set LimitToList to "No" then the user doesn't get a warning.
How can I achieve this behavior?
Ok, I tried this which works fine if the user selects YES, but becomes more complicated when the user selects "NO"
Public Function ReturnsRecords(strSQL As String) As Boolean
Dim d As DAO.Database
Dim arr(1 To 3) As DAO.Recordset
'Dim rs As DAO.Recordset
'assume 3 items in array above
Set d = CurrentDb
Set arr(1) = d.OpenRecordset(strSQL)
' MsgBox "Record Count is " & arr(1).RecordCount
If arr(1).RecordCount > 0 Then
ReturnsRecords = True
Else
ReturnsRecords = False
End If
Set d = Nothing
End Function
Private Sub cmbPROGRAM_BeforeUpdate(Cancel As Integer)
Dim strSQL As String
strSQL = "Select * from LU_PROGRAM where PROGRAM ='" & Me.cmbPROGRAM & "'"
If ReturnsRecords(strSQL) = False Then
If MsgBox("'" & Chr(34) & Me.cmbPROGRAM & Chr(34) & " hasn't been used yet. Add to list? ", vbQuestion + vbYesNo, "Add - " & Me.cmbPROGRAM & "?") = vbNo Then
Cancel = True
' how do I reset this? Me.cmbPROGRAM.Text = Null
End If
End If
End Sub
How do I clear the combobox if the user selects NO? If I select me.undo, that will undo all of the entries, but I just want to clear the combobox.
Incidentally, the form is totally unbound and doesn't accept an entry until the user selects "Save"
First, I'm not quite sure what you wish to achieve ...
Then, educate the users to press Escape to cancel. This is mandatory wisdom when operating an Access application.
For your code to work, you can't change the content of a control in the BeforeUpdate event. So try the AfterUpdate event with either:
Me!cmbPROGRAM.Text = ""
or:
Me!cmbPROGRAM.Value = Null

How to programmatically select rows in vb6 Datagrid

I have a VB6 Project I am creating and i have a method that searches and edits students from an access database. i need to code the program so it can select the student that was searched and modify it. I saw this webpage but it does not select the student, the user has to select it before making edits, https://support.microsoft.com/en-us/kb/195472 . How do i program it so it can select that particular row so the user can edit.
Code using the website:
Option Explicit
Dim connSearch As New ADODB.Connection
Dim rec As New ADODB.Recordset
Private Sub cmdSearch_Click()
connSearch.Close
connSearch.Open connstr
rec.CursorLocation = adUseClient
If cmbSearch.Text = "Last Name" Then
rec.Open "Select * From Table1 where [Last Name] like '" & txtSearch.Text & "'", connSearch, adOpenDynamic, adLockOptimistic
frmStudents.cmdShowall.Enabled = True
If rec.EOF Then
MsgBox "No Student Found.", vbInformation, "Error"
Else
Set frmStudents.StudentTable.DataSource = rec
MsgBox "Student found Successfully", vbInformation, "Success"
' Remove previously saved bookmark from collection
If (frmStudents.StudentTable.SelBookmarks.Count <> 0) Then
frmStudents.StudentTable.SelBookmarks.Remove 0
End If
' Append your bookmark to the collection of selected rows
frmStudents.StudentTable.SelBookmarks.Add rec.Bookmark
frmSearch.Hide
End If
End If
End Sub
Thanks for the help. :)
EDIT: Move code from comments to here
Private Sub Form_Load()
connSearch.Open connstr 'open the connection
frmStudents.Adodc1.ConnectionString = conn.connstr
Set frmStudents.StudentTable.DataSource = frmStudents.Adodc1
End Sub
You must be using a recordset to fill the frmStudents.Adodc1 Datasource but for some reason you don't want to show that code.
Then in the code you try you're opening a new recordset to search for the student and assign a bookmark. That will not work.
If you want to show all the students - like the example shows - you need to leave the data source alone and do the find on the same recordset used by your datagrid.
It's hard for me to guess what that is since you're not showing me the Form's code - I assume the recordset is global withing the form's module - but maybe not?
Without that information I can guess at something, hoping maybe the translation will work.
Replace this
rec.Open "Select * From Table1 where [Last Name] like '" & txtSearch.Text & "'", connSearch, adOpenDynamic, adLockOptimistic
frmStudents.cmdShowall.Enabled = True
If rec.EOF Then
MsgBox "No Student Found.", vbInformation, "Error"
Else
Set frmStudents.StudentTable.DataSource = rec
MsgBox "Student found Successfully", vbInformation, "Success"
' Remove previously saved bookmark from collection
If (frmStudents.StudentTable.SelBookmarks.Count <> 0) Then
frmStudents.StudentTable.SelBookmarks.Remove 0
End If
' Append your bookmark to the collection of selected rows
frmStudents.StudentTable.SelBookmarks.Add rec.Bookmark
frmSearch.Hide
With this
Dim varBookmark as Variant
With frmStudents.StudentTable
varBookMark = .Bookmark
' Remove previously saved bookmark from collection
If (.SelBookmarks.Count <> 0) Then
.SelBookmarks.Remove 0
End If
.Recordset.Find "[Last Name] like '" & txtSearch.Text & "'"
' If Find method fails, notify user
' If the search fails, the Recordset will point to either EOF or BOF.
If .Recordset.EOF or .Recordset.BOF Then
Msgbox "No Student Found"
' Reset back to last selection
.Recordset.Bookmark = varBookmark
Else
Msgbox "Student Found"
.SelBookmarks.Add .Recordset.Bookmark
Endif
End With
Ideally you'd just use the recordset variable that you assigned to frmStudents.Adodc1 instead of frmStudents.Adodc1.Recordset, but you haven't shared that with me so maybe this will work for you

Auto Populate Access Form using simple VBA code by setting a variable

I was recently given the task of creating a form that will autofill with the information from a table. The information the form autofills is selected using a primary key called ModID. I have a combo box that has a List of the ModIDs that are listed as Active.
SELECT ModID
FROM P_Review
WHERE Status = "Active"
Simple enough. I then have VBA code running on the event After Update. So after the value for the combo box is select or changed it will run this VBA code.
Option Compare Database
Option Explicit
Private Sub selectModID_AfterUpdate()
'Find the record that matches the control.
On Error GoTo ProcError
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID=" & Me.selectModID
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.RunCommand acCmdRecordsGoToNew
Me!localModID = Me.selectModID.Column(0)
End If
End With
ExitProc:
Exit Sub
ProcError:
MsgBox "Error: " & Err.Number & ". " & Err.Description
Resume ExitProc
End Sub
The code runs fine (I get no errors when I debug or run).
Now for the access text box. I would like to populate certain fields based off the variable localModID. I have a dlookup in a text box to find the information in the table P_Review.
=DLookUp("Threshold","P_Review","ModID =" & [localModID])
So the DlookUp should find the value for the column threshold, in the table P_Review, where the ModID in P_Review equals the localModID set in the VBA code. But when I go to form view and select a ModID I get the Error 3070: The Microsoft Access database engine does not recognize as a valid field name or expression. I did copy this code from another database we are already using but it fails in this new instance.
Private Sub ModID_AfterUpdate()
Dim rs As Object
Set rs = Me.RecordsetClone
With rs
.FindFirst "ModID='" & Me.ModID & "'"
If Not .NoMatch Then
Me.Bookmark = .Bookmark
Else
DoCmd.GoToRecord , , acNewRec
Me!ModID = Me.ModID
End If
End With
End Sub
This is the answer to question. I used this code to auto update.
Try
Forms!<whatever_this_form_name_is>![localModID]
in your DLOOKUP

Setting a value of a field in my table for future use

I have an access Db which was originally written ib Access 2003 but has since been upgraded to Access 2007 - the problem I am experiencing is as follows:
I have a table "tblBookings" which stores all relevant data for a particular clienst booking or quote, the client field of this table is linked to the PK of the CLient Table (tblClients) when a quote is accepted the user opens the main form, selects the client and in a dropdown selects the booking number then proceeds to "Edit booking" where the user can either edit the booking or confirm it. when the user clicks "confirm Booking" cmdButton the open form closes and the "Create Invoice" form opens. From a dropdown list the user selects the booking number and then prints the Pro-Forma Invoice or invoice. the print pro-forma cammand button opens a report that prints the necessary document, when the Print Invoice command is clicked then the print invoice form is opend where the user has the option to record any ayments made against the invoice.
This being said it is essential to first print a pro-forma before printing an invoice so i need to set a yes no field in the table to yes or true if a pro forma has been printed in which case the invoice button will become visible and remain hidden if one has not been printed yet.
the event procedure on cmdProForma is below (this is where I need ti set the yes/no field in the Pro field which is tblBookings and set to a yes/no field.
Private Sub CmdProForma_Click()
Dim rs As New ADODB.Recordset 'recordset of existing refs
Dim t As String 'temp string var
Dim stDocName As String
Dim stLinkCriteria As String
Dim i As Integer 'temp ref variable
i = CInt(Right(txtBRef, 5))
t = [txtBRef]
With rs
.Open "SELECT BRef,Conf,lock,Pro FROM tblBookings WHERE Bref=" & t & ";", CurrentProject.Connection, adOpenDynamic
If .BOF Or .EOF Then 'no such ref
MsgBox "No booking with ref '" & fRef(CInt(t), "B") & "' exists.", vbExclamation, "No booking"
Else 'ref found: open invoice
strSQL = "UPDATE tblBookings SET Pro = True"
'db.Execute strSQL, dbFailOnError
DoCmd.Close acForm, "frmBRefEnter"
' !Form!frmBRefEnter!Pro = True
DoCmd.OpenReport "rptInvoice1", acViewPreview, , "BRef=" & t
DoCmd.OutputTo acOutputReport, "rptInvoice1", acFormatPDF, destDIR & "\Inv\" & fRef(i, "Pro-Forma") & ".pdf"
End If
End With
End Sub
Add the checkbox for proforma printed to the form. It will be a good guide for your users as to why they cannot print an invoice. You can set the properties to Locked=True
Private Sub CmdProForma_Click()
''"From a dropdown list the user selects the booking number",
''so the booking number must exist, no need to check
DoCmd.OpenReport "rptInvoice1", acViewPreview, , "BRef=" & Me.txtBref
DoCmd.OutputTo acOutputReport, "rptInvoice1", _
acFormatPDF, destDIR & "\Inv\" & fRef(i, "Pro-Forma") & ".pdf"
Me.Pro = True ''Checkbox
DoCmd.Close acForm, "frmBRefEnter"
End Sub
For the invoice button:
Me.cmdInvoicePrint.Visible = Me.Pro
If Me.Pro is ticked, Me.Pro will be true and the invoice button will be visible.