Check if certain data exists in a field in a table - ms-access

I have a table (tblForms) in which one of the fields is a lookup to another table (tblClients). How can I find if a certain Client has data or does not have data in tblForms? DCount only works if the Client does appear in tblForms.
I have a form (frmDisclosure) with a command button - onClick:
Private Sub Command245_Click()
On Error GoTo Command245_Click_Err
DoCmd.OpenForm "frmClient", acNormal, "", "[ClientID]= " & Me.Client, , acNormal
DoCmd.Close acForm, "frmDisclosure"
Command245_Click_Exit:
Exit Sub
Command245_Click_Err:
MsgBox Error$
Resume Command245_Click_Exit
End Sub
When I click this I get the error (N.B. I f I open frmClient directly form Switchboard I don't get the error). frmClient has a subform (continuous) frmFormsList which derives its data from:
SELECT tblForms.ClientLookup, tblForms.Issued, First(tblForms.RefNo) AS FirstOfRefNo, Last(tblForms.RefNo) AS LastOfRefNo, Count(tblForms.RefNo) AS CountOfRefNo, tblClient.KnownAs, tblClient.EMail
FROM tblForms INNER JOIN tblClient ON tblForms.ClientLookup = tblClient.ClientID
GROUP BY tblForms.ClientLookup, tblForms.Issued, tblClient.KnownAs, tblClient.EMail
HAVING (((tblForms.Issued) Is Not Null));
This function resides in frmFormsList:
Public Function NumRecs() As Integer
NumRecs = DCount("*", "tblForms", "ClientLookup = " & Me.ClientLookup)
End Function
My query shows data where I have issued forms to a client. Therefore if I have not issued forms to a Client tne the query shows nothing for that client so does not give a result 0. I get RunTime Error 2427 "You entered ans expression that has no value". NumRecs = DCount("*", "tblForms", "ClientLookup = " & Me.ClientLookup) is highlighted in debug.
In frm Disclosure, if I Rem out ", acNormal, "", "[ClientID]= " & Me.Client, , acNormal" the problem does not occur, but I don't get straight to the Client I am interested in. So the problem occurs when I try to open a form using the Rem'd out bit where the client has not been issued with any forms. When I opne the frm Client directly the rocord presented does not have forms issued but the problem does not occur.

Here's the solution:
Public Function NumRecs() As Integer
Dim dbs As DAO.Database
Dim rs As Object
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("qryDisclosure", dbOpenDynaset)
If Me.Recordset.RecordCount = 0 Then
NumRecs = 0
Else
NumRecs = Nz(DCount("*", "qryDisclosure", "ClientLookup = " & Me.ClientLookup), 0)
End If
End Function

Related

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

VBA scripts no longer work after SQL migration

I recently migrated an Access database (that someone more knowledgeable than I designed) to MySQL, and linked the tables back into Access to use as a front end. Almost everything looks great. There is just one form and chunk of VBA code that doesn't seem to work. There is a form that should show drop down menus and controls, but is blank in form view. The form in design view and form view The VBA code that goes with the form is
Option Compare Database
Private Sub cmdPreviewPlate_Click()
'show user the new plate that is to be added to tblPCRsamples
On Error GoTo Err_cmdPreviewPlate_Click
'check whether boxes are blank
Dim bolBlank As Boolean
bolBlank = False
If IsNull(Me.Controls!cboChooseTemplatePlate) Then bolBlank = True
If IsNull(Me.Controls!cboChooseLocus) Then bolBlank = True
If IsNull(Me.Controls!txtEnterDate) Then bolBlank = True
If bolBlank = False Then
'enable the Add button
Me.Controls!cmdAddPlate.Enabled = True
'generate the unique PCRplate from the template plate number and locus
' using the global variable GstrPCRPlateName so that the queries can add the plate name to both tables
GstrPCRPlateName = Me.Controls!cboChooseTemplatePlate.Value & "_" & Me.Controls!cboChooseLocus
'check: does this PCRplate already exist in tblPCRplates?
Dim dbs As Database
Dim rst As Recordset
Dim bolDone As Boolean
Dim bolNameExists As Boolean
bolDone = False
bolNameExists = False
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tblPCRplates", dbOpenDynaset)
rst.MoveFirst
Do Until bolDone = True
'does the new plate name automatically generated here = the value of PCRplate in the current record?
If GstrPCRPlateName = rst![PCRPlate] Then
bolNameExists = True
bolDone = True
End If
rst.MoveNext
If rst.EOF Then bolDone = True
Loop
'if the name already exists, make a new name by appending _ and the date
If bolNameExists = True Then
GstrPCRPlateName = GstrPCRPlateName & "_" & Me.Controls!txtEnterDate
End If
'set the value for the Locus
GstrGetLocus = Me.Controls!cboChooseLocus
'open the select query to show user what they're going to add to the PCR plates & samples tables
Dim stDocName As String
stDocName = "qryNewPCR_1SelectTemplatePlate"
DoCmd.OpenQuery stDocName, acNormal, acReadOnly
Else
'if user left fields blank (except page number, that can be blank), show an error message
MsgBox "Choose/enter values for all the boxes"
End If
Exit_cmdPreviewPlate_Click:
Exit Sub
Err_cmdPreviewPlate_Click:
MsgBox Err.Description
Resume Exit_cmdPreviewPlate_Click
End Sub
Private Sub cmdAddPlate_Click()
'add this new plate to tblPCRplates and tblPCRsamples
On Error GoTo Err_cmdAddPlate_Click
'add the new plate to tblPCRplates
Dim stDocName As String
stDocName = "qryNewPCR_2AppendPlate"
DoCmd.OpenQuery stDocName, acNormal, acEdit
'run the query to append the samples to tblPCRsamples
stDocName = "qryNewPCR_3AppendSamples"
DoCmd.OpenQuery stDocName, acNormal, acEdit
'open frmPCRSamples to show the new plate has been added
stDocName = "frmPCRSamples"
DoCmd.OpenForm stDocName, acFormDS
Exit_cmdAddPlate_Click:
Exit Sub
Err_cmdAddPlate_Click:
MsgBox Err.Description
Resume Exit_cmdAddPlate_Click
End Sub
So my question is, should the linked tables be causing errors? Is there something I can amend to say that they are linked? Or am I barking up the wrong tree?
Thanks for your help. I know nothing of VBA (I mean, I can follow along) and have been tasked to destroy, I mean...admin...this database. This is what happens when you give biologists computers ;-) Even just some good resources would help a great deal.
The happens when your RecordSource of the form returns zero records and the form or record source does not allow adding new records.
Check the record source (table, query, or SQL string) and run it manually to see if it returns records.

Why do I get run-time error '2759' when saving the record? access 2010

Using Access 2010, I have a form for Purchase_Orders where the status changes depending on the whether the Items in the sub form have been delivered or not, and, it is influenced by the date as well.
Private Sub Form_AfterUpdate()
Dim rs As Recordset
Dim db As Database
Dim var_Delivered As String
var_Delivered = "SELECT Count(*) AS d_Count" & _
" FROM Items" & _
" WHERE PO_ID =" & Me.PO_ID.Value & _
" AND Supplier_Dnote_ID IS Null" & _
" AND Delivered_Without_Dnote =0;"
Set db = CurrentDb
Set rs = db.OpenRecordset(var_Delivered, dbOpenDynaset)
'MsgBox rs!d_Count
If rs!d_Count > 0 Then
If Me.Supply_date < Date Then
Me.Status = "Overdue"
Else
Me.Status = "Submitted"
End If
Else
Me.Status = "Delivered"
End If
db.Close
Set db = Nothing
Set rs = Nothing
End Sub
This runs after_update of the Purchase_Orders. I have a save_close button that uses the following code and doesn't return an error:
If Me.Dirty = True Then
DoCmd.Close acForm, "Purchase_Orders", acSaveYes
Else
DoCmd.Close acForm, "Purchase_Orders", acSaveNo
End If
However, I also have a Save button that doesn't close the form. This is where I get run-time error 2759 : The method you tried to invoke on an object failed. Debug Highlights the saverecord line.
Private Sub SaveOnlyBtn_Click()
If Me.Dirty = True Then
docmd.RunCommand acCmdSaveRecord
End If
End Sub
If I comment the status code out and use the save button, the record saves fine without any errors. Why do I get this error? I'm completely stumped and searching the error online hasn't helped me either.
So I found that the error did not occur when I put the code in the "on dirty" event, which then made me realise that I don't need necessarily have to run the code after the form updates, only when specific fields change. So I changed my code to a public code and called it when supply date, delivered_without_dnote, or supplier_Invoice_ID changed.
the public code is :
Public Sub delivered_status()
On Error GoTo errTrap1
If Forms!Purchase_Orders_Ex.Form!Status = "Cancelled" Then
Exit Sub
Else
DoCmd.RunCommand acCmdSaveRecord
Dim rs As Recordset
Dim db As Database
Dim var_Delivered As String
var_Delivered = "SELECT Count(*) AS d_Count" & _
" FROM Items" & _
" WHERE PO_ID =" & Forms!Purchase_Orders_Ex.Form!PO_ID.Value & _
" AND Supplier_Dnote_ID IS Null" & _
" AND Delivered_Without_Dnote =0;"
Set db = CurrentDb
Set rs = db.OpenRecordset(var_Delivered, dbOpenDynaset)
'MsgBox "Outstanding Items: " & rs!d_Count
If rs!d_Count > 0 Then
If Forms!Purchase_Orders_Ex.Form!Supply_date < Date Then
Forms!Purchase_Orders_Ex.Form!Status = "Overdue"
Else
Forms!Purchase_Orders_Ex.Form!Status = "Submitted"
End If
Else
Forms!Purchase_Orders_Ex.Form!Status = "Delivered"
End If
rs.Close
Set db = Nothing
Set rs = Nothing
End If
errTrap1:
Select Case Err.Number
Case 3314 'form not complete and other required fields are empty
Exit Sub
Case Else
If Err.Number > 0 Then
MsgBox Err.Number & ": " & Err.Description
End If
End Select
End Sub
Now, when I use either the save_close or Save_Only I do not get error 2759. I do not completely understand which part of my original method caused the error but it no longer occurs with this approach.
I've just encountered this issue and moving code out of Form_AfterUpdate fixed it for me too.
What's (vaguely) interesting is that the code in question worked fine locally, but did not work when deployed to the client. I tried importing just the amended form instead of replacing the whole access app, but I still got the same issue. I also copied the back-end database back from the server to my development machine, but still didn't get the issue locally. On top of that I did endless compact/repair and decompile/compile.
My conclusion at the end of all of that was that this was yet another weird issue emanating from the Access black-box, rather than an issue with the particular code.

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

Access query need to bypass "enter parameter value" error with a msg box saying field not found

I have a simple query tied to a command button that shows a summary of the values in a particular field. It's running on a table that changes with each use of the database, so sometimes the table will contain this field and sometimes it won't. When the field (called Language) is not in the file, the user clicks the command button and gets the "Enter Parameter Value" message box. If they hit cancel they then get my message box explaining the field is not present in the file. I would like to bypass the "Enter Parameter Value" and go straight to the message if the field is not found. Here is my code:
Private Sub LangCount_Click()
DoCmd.SetWarnings False
On Error GoTo Err_LangCount_Click
Dim stDocName As String
stDocName = "LanguageCount"
DoCmd.OpenQuery stDocName, acNormal, acEdit
Err_LangCount_Click:
MsgBox "No Language field found in Scrubbed file"
Exit_LangCount_Click:
Exit Sub
DoCmd.SetWarnings True
End Sub
You can attempt to open a recordset based on the query before you run the query:
Set rs = CurrentDb.QueryDefs("query1").OpenRecordset
This will go straight to the error coding if anything is wrong with the query.
Alternatively, if it is always the language field and always in the same table, you can:
sSQL = "select language from table1 where 1=2"
CurrentDb.OpenRecordset sSQL
This will also fail and go to your error coding, but if it does not fail, you will have a much smaller recordset, one with zero records.
You can easily enough get a list of fields in a table with ADO Schemas:
Dim cn As Object ''ADODB.Connection
Dim i As Integer, msg As String
Set cn = CurrentProject.Connection
Set rs = cn.OpenSchema(adSchemaColumns, Array(Null, Null, "Scrubbed"))
While Not rs.EOF
i = i + 1
msg = msg & rs!COLUMN_NAME & vbCrLf
rs.MoveNext
Wend
msg = "Fields: " & i & vbCrLf & msg
MsgBox msg
More info: http://support.microsoft.com/kb/186246
You have a command button named LangCount. It's click event has to deal with the possibility that a field named Language is not present in your Scrubbed table.
So then consider why a user should be able to click that command button when the Language field is not present. When the field is not present, you know the OpenQuery won't work (right?) ... so just disable the command button.
See if the following approach points you to something useful.
Private Sub Form_Load()
Me.LangCount.Enabled = FieldExists("Language", "Scrubbed")
End Sub
That could work if the structure of Scrubbed doesn't change after your form is opened. If the form also includes an option to revise Scrubbed structure, update LangCount.Enabled from that operation.
Here is a quick & dirty (minimally tested, no error handling) FieldExists() function to get you started.
Public Function FieldExists(ByVal pField As String, _
ByVal pTable As String) As Boolean
Dim blnReturn As Boolean
Dim db As DAO.Database
Dim fld As DAO.Field
Dim tdf As DAO.TableDef
Set db = CurrentDb
' next line will throw error #3265 (Item not found in this collection) '
' if table named by pTable does not exist in current database '
Set tdf = db.TableDefs(pTable)
'next line is not actually needed '
blnReturn = False
For Each fld In tdf.Fields
If fld.Name = pField Then
blnReturn = True
Exit For
End If
Next fld
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
FieldExists = blnReturn
End Function