Access VBA SQL Complie Error: Type Mismatch - sql

This following bit of code is placed in the On Load event of a form:
Dim LAOQWeekdaySQL As String
Dim LAOQWeekday As QueryDef
Dim EnqIDTest As String
EnqIDTest = Me.txt_EnquiryID.Value
LAOQWeekdaySQL = "SELECT tbl_Costing_Labour.EnquiryID, tbl_Costing_Labour.PhaseLabour, tbl_Costing_Labour.TotalPhaseLabourHours " & _
"FROM tbl_Costing_Labour " & _
"WHERE (((tbl_Costing_Labour.EnquiryID)= " & EnqIDTest & ") AND ((tbl_Costing_Labour.PhaseLabour) Like ""*weekday*""));"
Set LAOQWeekday = CurrentDb.QueryDefs("LAOQWeekdayQRY").SQL = LAOQWeekdaySQL
Me.txt_LAOQ_Weekday.Value = DSum("TotalPhaseLabourHours", "LAOQWeekdayQRY")
Essentially it returns records matching the Inquiry Number and sums the final column in the query and outputs it to a textbox on the form.
However, when I got run the form it gives me a
compile error: type mismatch
Prior to this I did try and use a temporary query but then the Dsum has no name to reference when performing its function so I changed it .CreateQueryDef, which work fine the first time. Thereafter, obviously, it threw an error saying the query already exists so I went down the route of .QueryDefs to update the SQL instead and now I get the mismatch error.
I cannot see anything obvious, what am I missing here?
Thank you in advance for any help you can provide!

The following line evaluates to a Boolean:
Set LAOQWeekday = CurrentDb.QueryDefs("LAOQWeekdayQRY").SQL = LAOQWeekdaySQL
Try changing it to this:
Set LAOQWeekday = CurrentDb.QueryDefs("LAOQWeekdayQRY")
LAOQWeekday.SQL = LAOQWeekdaySQL

Related

VBA dictionary as a property of a class

I have this simplified class named clsWarehouseSum.
Option Compare Database
Option Explicit
Private wh_units As Scripting.Dictionary
Public Function availableUnits(warehouse As String) As Long
'Debug.Print wh_units(warehouse)
If wh_units Is Nothing Then Set wh_units = New Scripting.Dictionary
If Not wh_units.Exists(warehouse) Then
Dim SQL As String
Dim RS As DAO.Recordset
SQL = "SELECT sum(units) as tot_units " _
& "FROM warehouse " _
& "WHERE warehouse = '" & warehouse & "' "
Set RS = CurrentDb.OpenRecordset(SQL)
wh_units.Add (warehouse), RS("tot_units")
End If
availableUnits = wh_units(warehouse)
End Function
I try to use it like this:
Sub test()
Dim wh As New clsWarehouseSum
Debug.Print wh.availableUnits("Cohasset")
Debug.Print wh.availableUnits("Cohasset")
End Sub
While the first Debug.Print prints what's expected, the second one gives me an error:
Run time error 3420, Object Invalid or no longer set. When I step through the code, it correctly evaluates both if statements as false. Yet, the last line of the function gives me the error mentioned above. What am I doing wrong?
Why?
Add Debug.Print TypeName(wh_units(warehouse)) before the availableUnits = wh_units(warehouse) line and if it prints anything else than Long to the Immediate window then you might want to cast to Long using CLng while you also have some error handler in place.
Or, you might want to make sure that the line wh_units.Add (warehouse), RS("tot_units") is adding a Long to your dictionary so you should check the type before you add.
As a general rule, when you return a specific data type from a dictionary or collection, you should always have checks in place either when you add the data to the dict/coll or when you return it so that you avoid type incompatibility and runtime errors.

Make pre-prepared sql command in libreoffice basic

I'm trying to make a prepared query based on the value in a field in my form in libreoffice basic.For this, I created a macro.
But it returns an error on the query line saying
BASIC syntax error.
Unexpected symbol: oInstruction_SQL
Sub concatMotherName
Dim oSourceDonnees As Object
Dim oConnexion As Object
Dim stSql As String
Dim oResultat As Object
oSourceDonnees = thisComponent.Parent.dataSource
oConnexion = oSourceDonnees.getConnection("","")
oInstruction_SQL = oConnexion.createStatement()
Dim valueData As String
Dim dateLabel As String
valueData = ThisComponent.Drawpage.Forms.getByName("Form").getByName("id_mother_label").getCurrentValue()
stSql = "SELECT NOM_MERE FROM ""T_MOTHER"" WHERE ""NUM_MOTHER"" = ?" _
oInstruction_SQL = = oConnection.prepareStatement(stSql)
oInstruction_SQL.setString(1, valueData)
oResultat = oInstruction_SQL.executeQuery(stSql)
If Not IsNull(oResultat) Then
oResultat.Next()
MsgBox oResultat.getString(1)
End If
End Sub
There are two syntax problems. The first is the _ after the query string, which indicates that the next line is a continuation of that one. It's not a continuation, so remove it.
The second error is on the next line: = =.
When these errors are fixed, the code compiles successfully.

Access VBA Run-time error 3078, or Type Mismatch on DCount function

Objective: I'm building VBA code to filter through an address table SunstarAccountsInWebir_SarahTest. I want to loop through first and see if the address is "valid".
If it is not valid – export to different table.
If it is valid – it enters another nested if/then within "valid" address rows:
If their ID, external_nmad_id matches the ID of the second table 1042s_FinalOutput_7, I want to update one of the columns in the second table box13c_Address.
If it doesn't match an ID of the second table – it will be exported to a different table.
My problem is when I run my code it is returning
Run-Time error 3078: cannot find table or query
(it's breaking at the line where I compare the value of the cell (as string) against the DCount of table 2). If I remove the quotes around it I get a different error:
Type mismatch against the DCount
I feel like I'm missing something simple but can't tell what. How can I get my code to match a string value called in !external_nmad_id against the rest of the table called in my string? DCount("[ID]", StrSQL1)
Public Sub EditFinalOutput2()
'set variables
Dim i As Long
Dim qs As DAO.Recordset
Dim ss As DAO.Recordset
Dim StrSQL1 As DAO.Recordset
Dim IRSfileFormatKey As String
Dim external_nmad_id As String
Dim nmad_address_1 As String
Dim nmad_address_2 As String
Dim nmad_address_3 As String
Dim mytestwrite As String
'open reference set
Set db = CurrentDb
Set qs = db.OpenRecordset("SunstarAccountsInWebir_SarahTest")
'Set ss = db.OpenRecordset("1042s_FinalOutput_7")
'Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID
'FROM 1042s_FinalOutput_7;")
With qs.Fields
intCount = qs.RecordCount - 1
For i = 0 To intCount
If (IsNull(!nmad_address_1) Or (!nmad_address_1 = !nmad_city) Or (!nmad_address_1 = !Webir_Country) And IsNull(!nmad_address_2) Or (!nmad_address_2 = !nmad_city) Or (!nmad_address_2 = !Webir_Country) And IsNull(!nmad_address_3) Or (!nmad_address_3 = !nmad_city) Or (!nmad_address_3 = !Webir_Country)) Then
DoCmd.RunSQL "INSERT INTO Addresses_ToBeReviewed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
Else:
Set ss = db.OpenRecordset("1042s_FinalOutput_7")
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
If !external_nmad_id = DCount("[ID]", StrSQL1) Then
ss.Edit
ss.Fields("box13c_Address") = qs.Fields("nmad_address_1") & qs.Fields("nmad_address_2") & qs.Fields("nmad_address_3")
ss.Update
Else: DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Addresses_NotUsed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
DoCmd.SetWarnings True
End If
End If
qs.MoveNext
Next i
End With
'close reference set
qs.Close
Set qs = Nothing
ss.Close
Set ss = Nothing
End Sub
The issue is that the DCount function cannot operate directly against a Recordset.
You are declaring StrSQL1 as a RecordSet object and setting it to a RecordSet based on your Select statement.
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
You are then trying to pass this RecordSet to the DCount function which cannot accept a RecordSet object as the Domain parameter. As you can see in MSDN the DCount function requires a String parameter in the second position to define the "query" that you wish to "Count". Hence the 3078 error. When you remove the quotes around [ID] in your DCount line, you get Type Mismatch as a compile error because [ID] is not a String or String variable.
After you resolve that, you might want to reconsider your If statement. You haven't provided a sample of what kind of value !external_nmad_id will contain, other than the fact that it is a String value. The DCount function is going to return the number of rows found in the Domain (query) that you told it to count, so it appears you will be comparing a string (which may possibly contain alpha characters) to a number. Access will implicitly convert the DCount numeric result to a String for the sake of the comparison, but if your !external_nmad_id String is truly 10 characters or contains alpha characters, they will never match.
You cannot use a VBA recordset inside a domain aggregate like DCount as a string literal is required for table/query name argument. Simply save your query and then reference it by name in DCount.
SQL (save as query)
SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;
VBA
If !external_nmad_id = DCount("[ID]", "mySavedQuery") Then
...
End If

how to set result of aggregate sql query as lable caption

I am using this code to retrieve no of machines (count)...
Dim strCntSr As String = "SELECT count(sr_no) FROM Vendor_Machine WHERE chaln_no='" & cmbChal_no.Text & "'"
comm_getCnt = New OleDb.OleDbCommand(strCntSr, cnnOLEDB)
comm_getCnt.ExecuteNonQuery()
***Here I want to set result of the above query [count(sr_no)] as text of lblMachine***
lblMachine.Text =
Please suggest me the code.. Thank you..
ExecuteNonQuery return only the number of the rows affected not the value/s returned by the query.
In your case the correct method to use is ExecuteScalar that returns the first column of the first row obtained by the query.
Notice also that is a very bad practice to build query text using string concatenation.
The problems are Sql Injection and correct parsing of text provided by you.
Dim strCntSr As String = "SELECT count(sr_no) FROM Vendor_Machine WHERE chaln_no=?"
comm_getCnt = New OleDb.OleDbCommand(strCntSr, cnnOLEDB)
comm_getCnt.Parameters.AddWithValue("#p1", cmbChal_no.Text)
Dim result = comm_getCnt.ExecuteScalar()
lblMachine.Text = Convert.ToInt32(result);

Linq - Value of type 'System.Guid' cannot be converted to 'String'

I'm using Linqer to convert SQL to Linq:
Update EmployeeSite SET SiteId = Null
WHERE SiteId = '86086EC5-567A-46B3-8DFC-E624F9B0324B'
Gets translated into:
Dim queryEmployeeSites = _
From employeesites In rdc.EmployeeSites _
Where _
CStr(employeesites.SiteId) = "86086EC5-567A-46B3-8DFC-E624F9B0324B" _
Select employeesites
For Each employeesites As EmployeeSite In queryEmployeeSites
employeesites.SiteId = Nothing
Next
rdc.SubmitChanges()
But when I try to run the Linq code I get the error message:
Error Compiling Expression: Error Compiling Expression: Value of type 'System.Guid' cannot be converted to 'String'.
I am very new to Linq. Can someone please explain what is wrong?
Thanks!
You can replace CStr(employeesites.SiteId) with employeesites.SiteId.ToString(), but the best is to compare the other way around
employeesites.SiteId = Guid.Parse("86086EC5-567A-46B3-8DFC-E624F9B0324B")
This way you don't run into issues with different capitalization, etc.
Dim queryEmployeeSites = _
From employeesites In rdc.EmployeeSites _
Where _
employeesites.SiteId.ToString().Equals("86086EC5-567A-46B3-8DFC-E624F9B0324B") _
Select employeesites
For Each employeesites As EmployeeSite In queryEmployeeSites
employeesites.SiteId = Nothing
Next
rdc.SubmitChanges()
Calling ToString() instead should work, also it's better to use Equals for String Equality, or use String.Compare.