Checking Null Value in Access VBA recordset throws null exception? - vba

I have tried this every different way, and it was working yesterday, so I really don't know what changed.
I import a spreadsheet to a temp table in an Access app. Then I set that to be the dao.recordset, and start looping through. I check for the ID to not be null and if not go through checking fields for values, and updating as appropriate. the minute I hit a null, I get a system error "94 - invalid use of null"
It doesn't offer a debug, but I have debugs throughout my code, so I can see where it fails. It fails when I do this check: If IsNull(rstImportCList("columnx")) = False Then
I have tried nz(rstImportCList("columnx"),"") <> "" I have tried rstImportCList("columnx") is not null, and everything else I can think of. Why is the check that is supposed to prevent this error, causing this error?
Edit:
This is the beginning where I declare the recordset I can't get past doing anything with the recordset field.
Dim db As DAO.Database
Dim rstImportCList As DAO.Recordset
Dim RSsql As String
Set db = CurrentDb()
RSsql = "Select * from tblTempImportCList"
Set rstImportCList = db.OpenRecordset(RSsql)
If rstImportCList.EOF Then Exit Sub
Do While Not rstImportCList.EOF
whether I try to check
IsNull(rstImportCList("xyz").Value) = False
or
nz(rstImportCList("xyz").Value,"") <> ""
or
dim x as string
x = rstImportCList!xyz.value
I get the same error 94 invalid use of null.
Any idea why this is?
--edit with more code.
I took some time to take a the beginning and some of each section of the code, so I could make it generic and see if anyone can help. Here is what I am working on. The Code1 and Code2 parts don't seem to be the issue. Sometimes it fails on a null value in a Yes/No column (I'm just looking for Y but the value is null), sometimes on the notes being null. It's not consistent, which is why I'm having a hard time nailing down the issue.
Private Sub cmdImportList_Click()
On Error GoTo cmdImportExcel_Click_err:
Dim fdObj As FileDialog
Set fdObj = Application.FileDialog(msoFileDialogFilePicker)
Dim varfile As Variant
Dim importCT As Integer
Dim dbu As DAO.Database
Dim cBadXVal, cBadYVal As Integer
Dim preNotes As String
Dim RSsql As String
Dim uNotesql, uVal1sql, uVal2sql As String
Dim db As DAO.Database
Dim rstImportCList As DAO.Recordset
Dim CheckB4Import As Integer
CheckB4Import = MsgBox("Are you SURE the sheet you are importing has the following column names in the same order:" & vbCrLf & vbCrLf & _
"IDName/ First/ Mid/ Last/ Sfx/ Age/ Telephone/ Code1/ Code2/ YN1/ YN2/ NY3/ Notes/ AsYN1edTo" & vbCrLf & vbCrLf & _
"AND that there are NO empty rows or empty columns?" & vbCrLf & vbCrLf & _
"Click OK to proceed, Click CANCEL to go double-check your CallSheet before importing.", vbOKCancel, "WITH GREAT POWER COMES GREAT RESPONSIBILITY TO QC DATA")
If CheckB4Import = vbOK Then
CurrentDb.Execute "DELETE * FROM tblTempImportCList", dbFailOnError
With fdObj
'CAN ONLY SELECT 1 FILE
.allowmultiselect = False
.Filters.Clear
.Filters.Add "Excel 2007+", "*.xlsx"
.Title = "Please select the completed list to import:"
.Show
If .SelectedItems.Count = 1 Then
varfile = .SelectedItems(1)
DoCmd.TransferSpreadsheet acImport, , "tblTempImportCList", varfile, True, "Sheet1!"
cBadXVal = DLookup("BadXCount", "qryImpCheckBadXVal")
Debug.Print "cBadXVal - " & cBadXVal
If cBadXVal <> 0 Then
DoCmd.OpenForm "frmImportError", acNormal
Forms!frmImportError.Form.lblErrorMsg.Caption = _
"Oh No! Your list import failed!" & vbCrLf & _
cBadXVal & " X values are not valid." & vbCrLf & _
"Don't worry. You can fix your sheet and re-import!" & vbCrLf & _
"Would you like to open the documentation for the valid codes" & vbCrLf & _
"Or are you all set?"
End If
cBadYVal = DLookup("BadYCount", "qryImpCheckBadYVal")
Debug.Print "cBadYVal - " & cBadYVal
If cBadYVal <> 0 Then
DoCmd.OpenForm "frmImportError", acNormal
Forms!frmImportError.Form.lblErrorMsg.Caption = _
"Oh No! Your list import failed!" & vbCrLf & _
cBadYVal & " YN1 values are not valid." & vbCrLf & _
"Don't worry. You can fix your sheet and re-import!" & vbCrLf & _
"Would you like to open the documentation for the valid codes" & vbCrLf & _
"Or are you all set?"
Exit Sub
End If
Else
MsgBox "No file was selected. Try again!", vbCritical, "Uh-oh Spaghettios!"
End If
End With
'PASSED CHECKS
Set db = CurrentDb()
RSsql = "Select * from tblTempImportCList"
Set rstImportCList = db.OpenRecordset(RSsql)
If rstImportCList.EOF Then Exit Sub
Debug.Print "got here"
Do While Not rstImportCList.EOF
Debug.Print "Start Processing: " & Nz(rstImportCList("IDName").Value, "")
'GET NOTES ALREADY ON RECORD
If Nz(rstImportCList("IDName").Value, "") <> "" Then
Debug.Print "got past if IDName is not null"
If Nz(rstImportCList("Notes").Value, "") <> "" Then
Debug.Print "got past if notes is not null"
preNotes = Replace(Nz(DLookup("Notes", "tblVFileImport", "IDName = " & rstImportCList("IDName").Value), ""), """", "")
'UPDATE NOTES
If Nz(preNotes, "") <> "" Then
uNotesql = "Update tblVFileImport SET tblVFileImport.Notes = '" & preNotes & "; " & Replace(Nz(rstImportCList("Notes").Value, ""), """", "") & "' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName").Value
'debug.print "Notes"
'debug.print "uNotesql - " & uNotesql
Else
uNotesql = "Update tblVFileImport SET tblVFileImport.Notes = '" & Replace(Nz(rstImportCList("Notes").Value, ""), """", "") & "' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName").Value
End If
RunMySql (uNotesql)
'DoCmd.RunSQL (uNotesql), dbFailOnError
End If
If Nz(rstImportCList("YN1").Value, "") = "Y" Then
'UPDATE YN1
uYN1sql = "Update tblVFileImport SET tblVFileImport.YN1 = '" & rstImportCList("YN1") & "', tblVFileImport.callprocessed = 'Y' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "YN1 = Y or y"
Debug.Print "uYN1sql - " & uYN1sql
RunMySql (uYN1sql)
'DoCmd.RunSQL (uYN1sql), dbFailOnError
End If
If Nz(rstImportCList("YN2").Value, "") = "Y" Then
'UPDATE YN2
uYN2sql = "Update tblVFileImport SET tblVFileImport.YN2 = '" & rstImportCList("YN2") & "', tblVFileImport.callprocessed = 'Y' " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "YN2 = Y or y"
Debug.Print "uYN2sql - " & uYN2sql
RunMySql (uYN2sql)
'DoCmd.RunSQL (uYN2sql), dbFailOnError
End If
'START Code1 PROCESSING
If Nz(rstImportCList("Code1").Value, "") <> "" Then
'Code1 Case abc
vdispo = DLookup("Code1", "tblvFileImport", "IDName = " & rstImportCList("IDName"))
If rstImportCList("Code1") = "ABC" Then
Debug.Print "Dispo Case ABC"
'DELETE RECORD
dMDsql = "DELETE from tblVFileImport " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "dMDsql - " & dMDsql
RunMySql (dMDsql)
'DoCmd.RunSQL (dMDsql), dbFailOnError
'Code1 Case DEF OR GHI OR JKL
ElseIf Nz(rstImportCList("Code1"), "") = "DEF" Or Nz(rstImportCList("Code1"), "") = "GHI" Or Nz(rstImportCList("Code1"), "") = "JKL" Then
Debug.Print "Dispo Case DEF OR GHI OR JKL "
'IF DEF
If rstImportCList("Code1") = "DEF" Then
'IF CELL SAME - UPDATE NULL
ccellsame = DLookup("IDName", "tblVFileImport", "IDName = " & rstImportCList("IDName") & " AND nz(Cell,'') = Phone ")
If ccellsame = rstImportCList("IDName") Then
uCellsql = "Update tblVFileImport SET tblVFileImport.Cell = NULL, tblVFileImport.CellString = NULL, tblVFileImport.mobileflag = NULL " & _
"WHERE tblVFileImport.IDName = " & rstImportCList("IDName")
Debug.Print "uCellsql - " & uCellsql
RunMySql (uCellsql)
'DoCmd.RunSQL (uCellsql), dbFailOnError
End If
End If
End If
End If
End If
Debug.Print "End Processing: " & rstImportCList("IDName")
rstImportCList.MoveNext
Loop
Debug.Print "Finished Looping"
rstImportCList.Close
importCT = DCount("IDName", "tblTempImportCList")
MsgBox importCT & " Records imported for list.", vbOKOnly, "List Processed"
Else
MsgBox "Good Call. Check twice, import once!", vbOKOnly, "Better Safe Than Sorry"
End If
Exit Sub
cmdImportExcel_Click_err:
Select Case Err.Number
Case Else
Call MsgBox(Err.Number & " – " & Err.Description, vbCritical + vbOKOnly, "System Error …")
End Select
End Sub
Any suggestions are greatly appreciated. I'm 1/2 tempted to suck this into a SQL table and just execute a stored procedure. I can get it to work in there, I think.

If IsNull(rstImportCList("columnx").Value) Then
otherwise you're checking if the Field object itself is null.
https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/field-object-dao#:~:text=To%20refer%20to,Fields(%22name%22)
This is a case where relying on a default property (in this case Value) causes problems.

Related

Loop through continuous form records and adding them to a table

Good afternoon,
I have a bound continuous form with a yes/no checkbox for each of the records shown. I'd like to have my users be able to click a "Select all" control and automatically have each one of those records be added to a different table.
So far, I have my loop working but not quite sure where to insert the proper code to add the records. I am using a frame control with a with a "Select all" "Deselect all" options. The [PrintPart] is the Yes/No field in the form.
Many thanks.
Private Sub SelectionFrame_Click()
Dim SQL as String
On Error GoTo errHandler
SQL = "INSERT INTO PARTS_T ([PRINTORDER], [PART_TITLE], [PARTID])
VALUES (" & Me.RecordsetClone.RecordCount + 1 & "," & Chr(34) &
Me.PART_TITLE & Chr(34) & "," & Me.PARTID & ");"
'Toggle select/deselect all
Select Case Me.SelectionFrame
Case 1 'Select
With Me.RecordsetClone
.MoveFirst
Do While Not .EOF
.Edit
!PrintPart = True
RunSQLCode
.Update
.MoveNext
Loop
End With
Case 2 'Deselect
With Me.RecordsetClone
.MoveFirst
Do While Not .EOF
.Edit
!PrintPart = False
.Update
.MoveNext
Loop
End With
End Select
Exit Sub
errHandler:
MsgBox "The following error has occurred: " & vbNewLine & vbNewLine & "Error Number: " & Err.Number & vbNewLine & "Error Description: " & Err.Description, vbCritical, "Error - " & APPNAME
End Sub
Don't run repeated SQL. DAO is way simpler and faster:
Private Sub SelectionFrame_Click()
Dim Source As DAO.Recordset
Dim Target As DAO.Recordset
Dim SQL As String
Dim PrintPart As Boolean
Dim PrintOrder As Long
On Error GoTo errHandler
Set Source = Me.RecordsetClone
PrintOrder = Source.RecordCount
If PrintOrder > 0 Then
SQL = "Select * From PARTS_T"
Set Target = CurrentDb.OpenRecordset(SQL, dbOpenDynaset, dbAppendOnly)
PrintPart = Me.SelectionFrame
Source.MoveFirst
While Not Source.EOF
If Source!PrintPart.Value <> PrintPart Then
Source.Edit
Source!PrintPart.Value = PrintPart
Source.Update
End If
Target.AddNew
Target!PRINTORDER.Value = PrintOrder + 1
Target!PART_TITLE.Value = Source!PART_TITLE.Value
Target!PARTID.Value = Source!PARTID.Value
Target.Update
Wend
Target.Close
End If
Source.Close
Exit Sub
errHandler:
MsgBox "The following error has occurred: " & vbNewLine & vbNewLine & "Error Number: " & Err.Number & vbNewLine & "Error Description: " & Err.Description, vbCritical, "Error - " & APPNAME
End Sub

MS Access+update Oracle SQL database from excel file

We have a Front end app created in MS Access and a back-end supported by an Oracle database.
The users are required to upload an Excel file (around 6000 rows) every day and the process is done currently like this:
we have a temporary table where a VBA code is moving the excel data (the table is empty at every load)
once the file is uploaded another VBA code is pulling the data from that table and moves it using DAO to the server, line by line
The process takes a huge amount of time and we need to speed up the process.
The existing code with some adjustments and fields not presented here:
Public Function import_to_dwh_old_1() As Boolean
Dim rst As DAO.Recordset
Dim strSQL As String
Dim bol As Boolean
Dim strSQL_hr As Object
Dim rs As DAO.Recordset
Dim cnt As Integer
Dim i As Integer
Dim varReturn As Variant
Dim HR_ID As String
'######## 05/26/2019 - Fix to upload multiple times per day the HR file
db.Execute ("DELETE FROM DISPUTE_MGMT.DD_HR WHERE SNAPSHOT='" & Format(GetUTC(), "mm/dd/yyyy") & "'")
'######## End fix to upload ###########
bol = True
strSQL = "Select * FROM temp_hr"
Set rst = db.OpenRecordset(strSQL, dbOpenSnapshot)
Set rs = db.OpenRecordset("DISPUTE_MGMT_DD_HR")
rst.MoveLast
rst.MoveFirst
cnt = rst.RecordCount
i = 1
Do While Not rst.EOF
On Error GoTo capture_error
'varReturn = SysCmd(acSysCmdSetStatus, "Uploading dispute " & i & " out of " & cnt & " for snapshot [" & Format(GetUTC(), "mm/dd/yyyy") & "]")
rs.AddNew
rs!USER_NAME = Environ("USERNAME")
rs!IS_DELETED = 0
rs!DATE_CREATED = GetUTC()
rs!DATE_MODIFIED = GetUTC()
rs!SNAPSHOT = Format(GetUTC(), "mm/dd/yyyy")
rs!HR_ID = rst!ID
'### deleted fields from code
rs.Update
rst.MoveNext
i = i + 1
Loop
varReturn = SysCmd(acSysCmdSetStatus, " ")
import_to_dwh = True
Exit Function
capture_error:
Debug.Print Err.Description
MsgBox Err.Description & " - HR_ID = " & HR_ID
varReturn = SysCmd(acSysCmdSetStatus, " ")
import_to_dwh = False
Exit Function
End Function
The new idea is more direct but I am not sure how to use in the same time a MS Access table and a SQL database table in the same statement
Public Function import_to_dwh() As Boolean
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Dim strSQL As String
On Error GoTo Error_Handler
Set qdf = CurrentDb.CreateQueryDef("")
If env = "prod" Then
qdf.Connect = prod_credentials
Else
qdf.Connect = dev_credentials
End If
'Delete current snapshot
qdf.SQL = "DELETE FROM DISPUTE_MGMT.DD_HR WHERE SNAPSHOT='" & Format(GetUTC(), "dd-mmm-yyyy") & "';"
Debug.Print qdf.SQL
qdf.ReturnsRecords = False
qdf.Execute
qdf.SQL = "INSERT INTO DISPUTE_MGMT.DD_HR (USER_NAME, IS_DELETED, DATE_CREATED, DATE_MODIFIED, SNAPSHOT, HR_ID) SELECT '" & Environ("USERNAME") & "', 0, to_date('" & GetUTC() & "','mm/dd/yyyy hh:mi:ss am'), to_date('" & GetUTC() & "','mm/dd/yyyy hh:mi:ss am'), " _
& "'" & Format(GetUTC(), "dd-mmm-yyyy") & "', ID FROM temp_hr;"
Debug.Print qdf.SQL
qdf.ReturnsRecords = False
qdf.Execute
Error_Handler_Exit:
On Error Resume Next
If Not rst Is Nothing Then
rst.Close
Set rst = Nothing
qdf.Close
Set qdf = Nothing
End If
import_to_dwh = True
'If Not db Is Nothing Then Set db = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: " & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
Dim L As Long
For L = 0 To Errors.Count - 1
Debug.Print Errors(L) & " - " & Errors(L).Description
Next
import_to_dwh = False
Resume Error_Handler_Exit
End Function
Obviously, the second method does not work.. Could someone point me to the right direction?
Thank you!

VBA/Access: How to stop "You... FORM to be active window"

I want to be able to tell IF a form is the active window.
It seems simply invoking that method produces an error. I guess I could catch that error and run with it, but it's a backwards way of doing it.
Screen.ActiveForm.Name
This needs a form to be active. If I am breaking any rules of stackOverflow please be kind and remind me as I am new to forum.
Screen.parent, screen.activeControl, etc. What if VBA editor is open, as often it is?
Function CStatus(strStatus, ByRef intType As Integer, Optional ByRef erNo, Optional erMsg, Optional strDatum)
'pXname = "CStatus"
'pXStack = Left(pXStack, 500) & ">" & pXname
'Updates and manages the status bar
Dim strPreamble As String, strOut As String, strForm As String, strComment As String, strSQL As String, strPxStack As String, strCErrStack As String
Dim intColor As Double
Dim intPreLen As Integer
'On Error GoTo err_hand
'Color Codes
'12632256 = Lt Grey
'33023 = Orange
'65280 = Green
'16744576 = Steel Grey
'Define "Constants"
intPreLen = 350 'Length of previous message cache
'** Fix missings
If (IsMissing(strDatum) = True) Then strDatum = "[N/A]"
'** Other inits
strWindow = Screen.Parent.Name
strForm = Screen.ActiveForm.Name
'** intDebug ' Minimum Level of to report to status
'bEcho = True 'Whether to echo to status
intColor = errNoColor(intType)
'Error-level idiot explanations
strComment = "0"
If IsMissing(erNo) Then erNo = 0
If (IsNull(erMsg) = False) Then
If IsMissing(erMsg) = False Then strComment = erMsg
End If
strComment = errorTree(erNo)
strPreamble = Left(strPreamble, intPreLen) & "..."
strErrStack = Left(strErrStack, intPreLen) & " > " & pXname & ":" & intType
strCErrStack = strErrStack
reS:
If ((strForm = "finvmain") Or (strForm = "fclips")) Then Screen.ActiveForm.timeStatusUpdated = Now() 'Small field keeps time
If bEcho = True Then
strPxStack = ""
strCErrStack = "" 'Internal error stack
End If
strOut = Now() & " " & intType & " (" & strType & "): " & erNo & " " & strCErrStack & " >> " & strComment & " / " & strStatus & " [" & strDatum & "] .. " & strPreamble
If bEcho = True Then
If (strForm = "fInvMain") Then Screen.ActiveForm.txtStatus2 = Screen.ActiveForm.txtStatus 'Added second window to show previous message
Screen.ActiveForm.txtStatus = strOut
End If
Screen.ActiveForm.txtStatus.ForeColor = intColor
If strForm = "fInvMain" Then strTag = Screen.ActiveForm.Controls("txttag").value
'***Event Log
If erNo = "" Then erNo = 0
If IsMissing(erMsg) = True Then erMsg = ""
If IsMissing(strDatum) = True Then strDatum = ""
If Len(strPreamble) < 2 Then strPreamble = "[None]"
'Fixxed - Syntax Error for Some Odd Reason! Apr 27th
If ((strTag = Empty) And (strForm = "fInvMain")) Then strTag = Screen.ActiveForm.txtTag 'Attempt to add tag# to entry
strStatus = cleanString(strStatus)
strDatum = cleanString(strDatum)
strComment = cleanString(strComment)
strSQL = "INSERT INTO tEvents(txtdate, myerrno, interrno, myerrmsg, interrmsg, txtform, stack, process, Datum, idLink) VALUES ('" & Now() & "','" & intType & "','" & erNo & "','" & strStatus & "','" & strComment & "','" & strForm & "','" & strErrStack & "','" & pXname & "','" & strDatum & "','" & strTag & "');"
CurrentDb.Execute strSQL, dbFailOnError
Exit Function
err_hand:
If Err.Number = 2475 Then
bEcho = False
Resume reS
Else: MsgBox "555: CStatus Internal Error, Turn off error handling to view"
End If
End Function
I need a boolean true or false IF form is active. If it isn't, I can't put stuff into a textbox in that.
To determine if a particular form is open then set focus to form:
If CurrentProject.AllForms("finvmain").IsLoaded
strForm = "finvmain"
Elseif CurrentProject.AllForms("fclips").IsLoaded Then
strForm = "fclips"
End If
If strForm <> "" Then DoCmd.SelectObject acForm, strForm

VBA in ACCESS how "Flag" and "Err05" got declared ?

I do not understand where "Flag and Err05" (at the bottom of the codes)have been declared ? I have searched the entire project and can not found where the two parameters got declared. When I try to use the below codes in another project , i got the error message "Run time error : items not found in this collection " Any answers?
>Private Sub SanityCheck_Click()
>Dim St As String, WrnFlag As Boolean, j As Integer
>Dim RS As Recordset, RS1 As Recordset, i As Integer, WrongRootCauses As String
>Dim Err01 As String, Err02 As String, Err03 As String, Err04 As String
>WrnFlag = False
>If IsNull(Me.FactoryList) Then
> MsgBox "Select valid Factory before proceeding.", vbExclamation
>Else
> St = "SELECT Factory, Step1, Step2, Step3, Step4, DateColumn FROM [tbl >Factory] WHERE Allowed = True and Factory = """ & Me.FactoryList.Value & """"
> Set RS = CurrentDb.OpenRecordset(St, dbOpenSnapshot)
'-- 12NC codes check --
> St = "SELECT Count([" & RS!Step2 & "].PLANT) AS 12NC_chk " & _
>"FROM [" & RS!Step2 & "] " & _
> "WHERE (((Len(Trim(IIf(Left(Trim([12NC_CODE]),3)=""000"",Right>([12NC_CODE],Len([12NC_CODE])-3),[12NC_CODE])))) Not In (0,1,12)));"
' "WHERE (((Len(Trim([12NC_CODE]))) Not In (0,1,12)));"
> Set RS1 = CurrentDb.OpenRecordset(St, dbOpenSnapshot)
>If RS1.BOF And RS1.EOF Then
> Err05 = "+ No 12NC issues found."
>Else
> RS1.MoveFirst
> RS1.MoveLast
> If RS1![12NC_chk] = 0 Then
> Err05 = "+ No 12NC issues found."
> Else
> Err05 = "- " & RS1![12NC_chk] & " Incorrect 12NCs found!"
> WrnFlag = True
> End If
> End If
'--
> If WrnFlag = True Then **Flag** = vbCritical Else **Flag** = vbInformation
> MsgBox RS!Factory & " input data sanity check:" & vbCrLf & vbCrLf & " " & >Err01 & vbCrLf & " " & Err02 & vbCrLf & " " & Err03 & _
> vbCrLf & " " & Err04 & vbCrLf & " " & Err05 & vbCrLf & vbCrLf & IIf>>(WrongRootCauses = "", "", " Unknown ADP Root Cause(s):" & vbCrLf & WrongRootCauses), Flag
> RS.Close
>RS1.Close
>End If
>End Sub
Two posibilities
Unless the file have Option explicit in the top, you are not forced to explicitely declare variables. Which means that Flag and Err05 have indeed never been declared. VBA will just create them on the fly with a Variant type and an initial value of Nothing.
They might be global variables declared outside of any sub in another file. Try right clicking the variable and then click definition in the menu, Access will show you the way.

Field name confusion

rs2.FindFirst "[aniin] ='" & strTemp & "'"
aniin being an alias from the SQL within the function.
also tried ...
rs2.FindFirst (niin = newdata)
is my attempt to isolate the field name niin from the record value in the form from the one in the strSQL2. All my attempts have failed. I am trying to make sure that what the user typed in does match the list from the SQL string.
Private Function IsPartOfAEL(newdata) As Boolean
On Error GoTo ErrTrap
Dim db2 As DAO.Database
Dim rs2 As DAO.Recordset
Dim strTemp As String
strSQL2 = "SELECT tbl_ael_parts.master_ael_id, tbl_master_niin.niin as aniin " & vbCrLf & _
"FROM tbl_master_niin INNER JOIN tbl_ael_parts ON tbl_master_niin.master_niin_id = tbl_ael_parts.master_niin_id " & vbCrLf & _
"WHERE (((tbl_ael_parts.master_ael_id)= " & Forms!frm_qry_niin_local!master_ael_id & "));"
Set db2 = CurrentDb
Set rs2 = db2.OpenRecordset(strSQL2)
strTemp = newdata
If rs2.RecordCount <> 0 Then
rs2.FindFirst "[aniin] ='" & strTemp & "'"
If rs2.NoMatch Then
IsPartOfAEL = False
Else
IsPartOfAEL = True
End If
Else
MsgBox "Query Returned Zero Records", vbCritical
Exit Function
End If
rs.Close
Set rs2 = Nothing
Set db2 = Nothing
ExitHere:
Exit Function
ErrTrap:
MsgBox Err.description
Resume ExitHere
End Function
First: You should never include a constant like vbCrLf when building a query string. The query parser doesn't care if there's a linefeed, and in fact this can sometimes cause issues.
Your code seems to do nothing more that verify whether the value in newdata exists in the tbl_ael_parts and is associated with the value master_ael_id value currently showing on frm_qry_niin_local. If so, then just use DCount, or use this for your query:
strSQL2 = "SELECT tbl_ael_parts.master_ael_id INNER JOIN tbl_ael_parts ON
tbl_master_niin.master_niin_id = tbl_ael_parts.master_niin_id WHERE (((tbl_ael_parts.master_ael_id)=
" & Forms!frm_qry_niin_local!master_ael_id & ") AND niin=" & newdata & ");"
Dim rst As DAO.Recordset
Set rst = currentdb.OPenrecordset(strsql2)
If (rst.EOF and rst.BOF) Then
' no records returned
Else
' records found
End If
If niin is a Text field:
strSQL2 = "SELECT tbl_ael_parts.master_ael_id INNER JOIN tbl_ael_parts ON
tbl_master_niin.master_niin_id = tbl_ael_parts.master_niin_id WHERE (((tbl_ael_parts.master_ael_id)=
" & Forms!frm_qry_niin_local!master_ael_id & ") AND (niin='" & newdata & "'));"
If both niin and master_ael_id are Text fields:
strSQL2 = "SELECT tbl_ael_parts.master_ael_id INNER JOIN tbl_ael_parts ON
tbl_master_niin.master_niin_id = tbl_ael_parts.master_niin_id WHERE (((tbl_ael_parts.master_ael_id)=
'" & Forms!frm_qry_niin_local!master_ael_id & "') AND (niin='" & newdata & "'));"