Access 2016 Run time error invalid use of null - vba

I am checking to see if a record exists in a Access 2016 form if it exist show a message if not add it to the database. But I am getting a invalid use of null when txtRepGrpNumber is empty, if not empty it adds it even though it already exists in the database. RepGrpNumber is a numeric field in the database. It errors out on my if statment.
Private Sub btnSave_Click()
Dim db As DAO.Database
Dim strSql As String
Dim message As String
Set db = CurrentDb
If Nz(CStr(Me.txtRepGrpNumber)) >= "" Then
strSql = "INSERT INTO dbo_TblSwShowRoom(RepGrpNumber, ViewOrder, RepCompany, AddressFull, Contact, Phone, Hours, ViewPhotos, ViewTour, ImageShow, Image, AddBy, DateAdded, DateChanged, ChangedBy, Enabled) " & _
"VALUES('" & Me.txtRepGrpNumber & "','" & Me.txtViewOrder & "', '" & Me.txtRepCompany & "', '" & Me.txtAddressFull & "', '" & Me.txtContact & "', '" & Me.txtPhone & "', '" & Me.txtHours & "', '" & Me.txtViewPhotos & "', '" & Me.txtViewTour & "', '" & Me.txtImageShow & "', '" & Me.txtImage & "', '" & Me.txtAddBy & "', '" & Me.txtDateAdded & "', '" & Me.txtDateChanged & "', '" & txtChangedBy & "', '" & txtEnabled & "')"
db.Execute strSql
Me.SubFrmSwShowRoom.Requery
Else
message = MsgBox("Cannot save because Group Number is Blank", vbCritical)
End If
'End If
Me.Requery
End Sub

If CStr(Nz(Me.txtRepGrpNumber,"")) <> "" Then

CStr can't convert a Null value. CStr(Null) throws the same error you're getting. This should do:
If Nz(Me.txtRepGrpNumber, vbNullString) <> vbNullString Then

The reason you are getting invalid use of null is if the value of txtRepGrpNumber has not been changed since you opened the form, and it was null, CStr throws the error invalid use of null when it gets to that.
To fix it:
If Me.txtRepGrpNumber & vbNullString <> vbNullString Then

Related

Access Error Run-Time 2447 Insert into table

The Error shows its there is an Invalid of the . (Dot) Or ! operator
If IsNull(Me.m_1) Or IsNull(Me.u_1) Or Me.m_1 = "" Or Me.u_1 = "" Then
MsgBox "Please add all needed info"
Else
sqls = "INSERT INTO User_access (Application_ID, Modul_ID, username_ID, Clock_ID, Assinged_date, Assinged_by, Request_number) values('" & Me.A_1 & "', '" & Me.m_1 & "', '" & Me.u_1 & "', '" & Me.Clock_ID & "', '" & Date & "', '" & Me.Assinged_by & "', '" & Me.Request_number & "');"
DoCmd.RunSQL sqls
End If
I cannot see any error within the code So please Help me
Use Date():
sqls = "INSERT INTO User_access (Application_ID, Modul_ID, username_ID, Clock_ID, Assinged_date, Assinged_by, Request_number) values('" & Me.A_1 & "', '" & Me.m_1 & "', '" & Me.u_1 & "', '" & Me.Clock_ID & "', Date(), '" & Me.Assinged_by & "', '" & Me.Request_number & "');"
And no quoting of numeric values.

How to fix syntax error in UPDATE statment in Access VBA

I'm trying to build a database and ran into a problem with the syntax in an UPDATE statement. Does anyone know what's wrong with the statement?
I've tried adjusting the use of single and double quotes but it's still not working.
CurrentDb.Execute "INSERT INTO tbl_SponsorContacts (ContactName, ContactEmail, ContactPhone, SponsorID )" _
& " VALUES ('" & Me.txtContactName & "','" & Me.txtContactEmail & "', '" & Me.txtContactPhone & "' , '" & Me.txtSpnID & "')"
Else
CurrentDb.Execute "UPDATE tbl_SponsorContacts SET ContactName = " _
& " '" & Me.txtContactName & "', ContactEmail = '" & Me.txtContactEmail & "', " _
& " ContactPhone = '" & Me.txtContactPhone & "', SponsorID = '" & Me.txtSpnID & "', WHERE ContactID = '" & Me.txtContactID & "'"
End If
Exit Sub
I keep getting the 3144 syntax error which doesn't provide any hints as to the cause. Any help is appreciated.
UPDATE: Thanks to Jerry M. and forpas for suggesting to remove the comma before where. That helped but I am not getting an error 3061, "Too few parameters. Expected 1".
I will post a new question.
As #forpas mentioned in the comments, it looks like you have an extra ,
Try below:
CurrentDb.Execute "INSERT INTO tbl_SponsorContacts (ContactName, ContactEmail, ContactPhone, SponsorID )" _
& " VALUES ('" & Me.txtContactName & "','" & Me.txtContactEmail & "', '" & Me.txtContactPhone & "' , '" & Me.txtSpnID & "')"
Else
CurrentDb.Execute "UPDATE tbl_SponsorContacts SET ContactName = " _
& " '" & Me.txtContactName & "', ContactEmail = '" & Me.txtContactEmail & "', " _
& " ContactPhone = '" & Me.txtContactPhone & "', SponsorID = '" & Me.txtSpnID & "'WHERE ContactID = '" & Me.txtContactID & "'"
End If
Exit Sub ```

Getting SQL Syntax Error in INSERT INTO statement in Access 2010

I have written the following Insert Into statement in Access 2010 VBA:
Private Sub AddBPSSButton_Click()
' CurrentDb.Execute "INSERT INTO TabClearDetail(C_Site) VALUES(" & Me.C_Site & ")"
Dim strSQL As String
'MsgBox Me.[Clearance Applying For]
'MsgBox Me.[Contract Applying for]
'MsgBox Me.[C_Site]
'MsgBox Me.[C_SponsorSurname]
'MsgBox Me.[C_SponsorForename]
'MsgBox Me.[C_SponsorContactDetails]
'MsgBox Me.[C_EmploymentDetail]
'MsgBox Me.[C_SGNumber]
'MsgBox Me.[C_REF1DateRecd]
'MsgBox Me.[C_REF2DateRecd]
'MsgBox Me.[C_IDDateRecd]
'MsgBox Me.[C_IDNum]
'MsgBox Me.[C_CriminalDeclarationDate]
'MsgBox Me.[Credit Check Consent]
'MsgBox Me.[C_CreditCheckDate]
'MsgBox Me.[Referred for Management Decision]
'MsgBox Me.[Management Decision Date]
'MsgBox Me.[C_Comment]
'MsgBox Me.[C_DateCleared]
'MsgBox Me.[C_ClearanceLevel]
'MsgBox Me.[C_ContractAssigned]
'MsgBox Me.[C_ExpiryDate]
'MsgBox Me.[C_LinKRef]
'MsgBox Me.[C_OfficialSecretsDate]
strSQL = "INSERT INTO TabClearDetail(Clearance Applying For, Contract Applying for, " & _
"C_Site, C_SponsorSurname, C_SponsorForename, C_SponsorContactDetails, C_EmploymentDetail, " & _
"C_SGNumber, C_REF1DateRecd, C_RED2DateRecd, C_IDDateRecd, C_IDNum, " & _
"C_CriminalDeclarationDate, Credit Check Consent, C_CreditCheckDate, Referred for Management Decision, " & _
"Management Decision Date, C_Comment, C_DateCleared, C_ClearanceLevel, C_ContractAssigned, " & _
"C_ExpiryDate, C_LinkRef, C_OfficialSecretsDate) VALUES('" & Me.[Clearance Applying For] & "', " & _
"'" & Me.[Contract Applying for] & "', '" & Me.[C_Site] & "', '" & Me.[C_SponsorSurname] & "', " & _
"'" & Me.[C_SponsorForename] & "', '" & Me.[C_SponsorContactDetails] & "', " & _
"'" & Me.[C_EmploymentDetail] & "', '" & Me.[C_SGNumber] & "', '" & Me.[C_REF1DateRecd] & "', " & _
"'" & Me.[C_REF2DateRecd] & "', '" & Me.[C_IDDateRecd] & "', '" & Me.[C_IDNum] & "', " & _
"'" & Me.[C_CriminalDeclarationDate] & "', '" & Me.[Credit Check Consent] & "', '" & Me.[C_CreditCheckDate] & "', " & _
"'" & Me.[Referred for Management Decision] & "', '" & Me.[Management Decision Date] & "', " & _
"'" & Me.[C_Comment] & "', '" & Me.[C_DateCleared] & "', '" & Me.[C_ClearanceLevel] & "', " & _
"'" & Me.[C_ContractAssigned] & "', '" & Me.[C_ExpiryDate] & "', '" & Me.[C_LinKRef] & "', " & _
"'" & Me.[C_OfficialSecretsDate] & "');"
DoCmd.RunSQL (strSQL)
'MsgBox strSQL
End Sub
All The MsgBox calls work, so I believe I have typed all column names and text box names correctly. I am getting a Syntax error when I get to the DoCmd.RunSQL line. Have been staring at this for quite a while trying to see if I have missed a comma or speech mark or something, but am hoping maybe another set of eyes will see my mistake.
Any help will be greatly appreciated.
Thanks!
When you have spaces in your object names you need to enclose the full name in brackets. So where you have:
INSERT INTO TabClearDetail(Clearance Applying For, Contract Applying for,...
It should be
INSERT INTO TabClearDetail([Clearance Applying For], [Contract Applying for],...
For what it's worth I personally can't stand special characters in object names for exactly this reason, if it's not too late you should consider renaming your columns. Pascal Case is usually clear enough for compound names, e.g. ClearanceApplyingFor. Or use under scores - Clearance_Applying_For.
I also think the convention in Access is to qualify dates with # rather than single quotes, i.e. #01/01/2014#, instead of `01/01/2014'
Either you try enclosing the date fields with "#" instead of "'" or change your database's "SQL Server Compatible Syntax" property.

Why do I get a data type mismatch when trying to update an Access database ? ( with autonumber)

I'm trying to update a customer table from VB.NET with the following SQL statement:
Dim SQLstr As String = "UPDATE tblKlant SET NaamFirma='" & naamFirma & "', Straat='" & straat & "', Nummer = '" & nummer & "', Gemeente='" & gemeente & "', Postcode='" & postcode & "', TEL='" & tel & "', Fax='" & fax & "',Gsm='" & gsm & "', BtwNr='" & btwNr & "', Email ='" & email & "', Website='" & website & "', IBAN ='" & IBAN & "', BIC='" & BIC & "' WHERE ID='" & CInt(id) & "';"
mainForm.SQLcommand(SQLstr)
The error lies in the WHERE ID='" & CInt(id) & "';" part. This gives me an error:
Data type mismatch in criteria expression
Cause when I replaced it with something else the query worked. The ID is an autonumber by the way. I know you can't update an autonumber but you must be able to use it in the WHERE clause.
Thanks in advance

Getting text from text boxes on tab control

I have a form with a tabcontrol in it with 4 tabpages each has it's own texboxes and comboboxes, then I have a button outside of the tabcontrol wich builds a SQL string from all the values entered in these boxes even if some are left blank, the issue is that when i press the button i get a null reference exception and even when I use Try..Catch or on error resume next the compiler refuses to create the text string.
here is the code I have:
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
If Me.BankGuidTextBox.Text = vbNullString Then
Me.BankGuidTextBox.Text = Guid.Empty.ToString
End If
If Me.BankNumTextBox.Text = vbNullString Then
Me.BankNumTextBox.Text = 0
End If
If Me.NameTextBox.Text = vbNullString Or Me.CodeTextBox.Text = vbNullString Then
GoTo outofsub
End If
Try
Dim strSQL3 As String
strSQL3 = "USE MSILHR" & vbCrLf & _
"UPDATE employee SET Code = '" & Me.CodeTextBox.Text & "', Name = '" & Me.NameTextBox.Text & "', Latinname = '" & Me.LatinNameTextBox.Text & "', Barcode = '" & Me.BarcodeTextBox.Text & "', FirstName = '" & Me.FirstNameTextBox.Text & "', LastName = '" & Me.LastNameTextBox.Text & "', idFather = '" & Me.IdFatherTextBox.Text & "', idMother = '" & Me.IdMotherTextBox.Text & "', idBirthDate = '" & Me.IdBirthDateDateTimePicker.Text & "', idBirthplace = '" & Me.IdBirthPlaceTextBox.Text & "', idSex = '" & Me.IdSexComboBox.SelectedValue & "', idMaritalstat = '" & Me.IdMaritalstatComboBox.SelectedValue & "', idSmoker = '" & Me.IdSmokerComboBox.SelectedValue & "', idMilitary = '" & Me.IdMilitaryComboBox.SelectedValue & "', idRegistry = '" & Me.IdRegistryTextBox.Text & "', idNum = '" & Me.IdNumTextBox.Text & "', idAddress = '" & Me.IdAddressTextBox.Text & "', idNationality = '" & Me.IdNationalityTextBox.Text & "', idReligion = '" & Me.IdReligionComboBox.SelectedItem & "', idTel = '" & Me.IdTelTextBox.Text & "', idMobile = '" & Me.IdMobileTextBox.Text & "', idNotes = '" & Me.IdNotesTextBox.Text & "', jStartDate = '" & Me.JStartDateDateTimePicker.Text & "', jQuitDate = '" & Me.JQuitDateDateTimePicker.Text & "', jQuitReason = '" & Me.JQuitReasonTextBox.Text & "', jSocialSec = '" & Me.JSocialSecTextBox.Text & "', jSocialdin = '" & Me.JSocialdinDateTimePicker.Text & "', jSocialdout = '" & Me.JSocialdoutDateTimePicker.Text & "', jHoliday1 = '" & Me.JHoliday1ComboBox.SelectedValue & "', jHoliday2 = '" & Me.JHoliday2ComboBox.SelectedValue & "', jEmpStat = '" & Me.JEmpStatComboBox.SelectedValue & "', jEmail = '" & Me.JEmailTextBox.Text & "', jPrevvacs = '" & Me.JPrevvacsTextBox.Text & "', jAdminvacs = '" & Me.JAdminvacsTextBox.Text & "', jHealthvacs = '" & Me.JHealthvacsTextBox.Text & "', jUnpaidvacs = '" & Me.JUnpaidvacsTextBox.Text & "', DepartmentGuid = '" & Me.DepartmentGuidComboBox.SelectedValue.ToString & "', JobTitleGuid = '" & Me.JobTitleGuidComboBox.SelectedValue.ToString & "',SalarycalctypeGuid = '" & Me.SalarycalctypeGuidComboBox.SelectedValue.ToString & "', TeamGuid = '" & Me.TeamGuidComboBox.SelectedValue.ToString & "', WorkDays = '" & Me.WorkDaysTextBox.Text & "', DaHours = '" & Me.DaHoursTextBox.Text & "', OverTimeHourPrice = '" & Me.OverTimeHourPriceTextBox.Text & "', CutSalary = '" & Me.CutSalaryTextBox.Text & "',BasicSalary = '" & Me.BasicSalaryTextBox.Text & "', SpecialSalary = '" & Me.SpecialSalaryTextBox.Text & "',CurrencyGuid = '" & Me.CurrencyGuidComboBox.SelectedValue.ToString & "', BankGuid = '" & Me.BankGuidTextBox.Text & "', BankNum = '" & Me.BankNumTextBox.Text & "', PeriodGUID = '" & Me.EmpperiodCombo.SelectedValue.ToString & "'" & vbCrLf & _
"WHERE GUID = '" & Me.GUIDTextBox.Text & "'"
'"update employee set Picturepath = (select name from types where type = '660')+'\" & Me.NameTextBox.Text & "' where code = '" & Me.CodeTextBox.Text & "' AND Name = '" & Me.NameTextBox.Text & "'"
Dim dbConnection As New SqlConnection(connectionString)
' A SqlCommand object is used to execute the SQL commands.
Dim cmd As New SqlCommand(strSQL3, dbConnection)
' Open the connection, execute the command, and close the connection.
' It is more efficient to ExecuteNonQuery when data is not being
' returned.
dbConnection.Open()
cmd.ExecuteNonQuery()
dbConnection.Close()
MessageBox.Show("Record is updated.", _
"Data Addition Status", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch sqlExc As SqlException
MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'Me.EmployeeTableAdapter.Fill(Me.MSILHRDataset.employee)
ResetUI()
outofsub:
MsgBox("you need to add more information!", MsgBoxStyle.Information, "Error")
End Sub
Ok new update :
I entered some data left some text boxes empty but made sure all combo boxes has values selected in them and then pressed updatebutton I got the same problem, but I redid that changed the current tab selected to any other one (from the other four) and then switched back to the previous tab, I press the button and IT WORKS!!?? it's as if the form doesn't Commit the values entered by user until focus changes or something it's crazy.
You are only catching a SqlException.
You need to also catch a general exception.
Catch sqlExc As SqlException
MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch exc As Exception
MessageBox.Show(exc.ToString, "General Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Not sure why you are getting a null exception.
But it is not caught because it is not a SqlException.
On that String break it down do see where it is breaking.
On the surface it looks like it should work.
I suspect one of the controls is returning null rather than string.empty.