Access VBA creating a query that uses a variant as a where condition - vba

I am trying to write a vba code that will create a query in Access with a where condition based off of the value of a cell from another table. My issue is that when I am trying to pull a string from the varRecords(0,0) Variant it becomes a parameter for the new query and not a string. I tried using cstr() function but it was still becoming a parameter. If I use msgbox to test what is being created it appears as a string. I may have left some stuff out of the code but the basics are below.
Dim dbsEmails As DAO.Database
Dim rstEmails As DAO.Recordset
Dim varRecords As Variant
Dim RecordCounter As Long
Dim qdfTemp As QueryDef
Dim strSQL As String
Dim strSQL2 As String
Set dbsEmails = CurrentDb
strSQL = "Select Email, ID from tbl_Email"
Set rstEmails = dbsEmails.OpenRecordset(strSQL, dbOpenSnapshot)
rstEmails.MoveLast
RecordCounter = rstEmails.RecordCount
rstEmails.MoveFirst
varRecords = rstEmails.GetRows(RecordCounter)
strSQL2 = "Select ID, Stuff from tbl2 Where id =" & varRecords(0,0)
SetqdfTemp = CurrentDb.CreateQueryDef("Pending Report", strSQL2)
End Function

Try making it a string:
strSQL2 = "Select ID, Stuff from tbl2 Where id = '" & varRecords(0,0) & "'"

Related

Check if table in Oracle database is empty using VBA and SQL COUNT(*)

I need how to find if a given table is empty in an Oracle database (Oracle 11g) to be specific using VBA inside of PowerAdmin Server Monitor's "run script" feature.
SELECT COUNT(*) FROM table; correctly returns "COUNT(*)" as 0. img of result
I need to find a way to check that result if it is 0 or not.
This is a redacted version of the script colleague uses to access the database for slightly different purposes, I prefer if we could continue from this
Dim strConnect
Dim strSQL
Dim adoConnection
Dim adoRecordset
strConnect = "Driver={Oracle in OraClient11g_home1_32bit};" & _
"Dbq=database;" & _
"Uid=user;" & _
"Pwd=password"
strSQL = "SELECT COUNT(*) FROM table;;"
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Open strConnect
Set adoRecordset = CreateObject("ADODB.Recordset")
adoRecordset.ActiveConnection = adoConnection
adoRecordset.Source = strSQL
adoRecordset.Open
[check if query result is the number 0 here]
adoRecordset.Close
adoConnection.Close
I need something that would look like
If queryresult = 0 then
SendNotification = True
Details = "table is empty"
End If
Any help would be appreciated. The more ELI5 the better.
After you execute a query in ADO, the recordset points to the first record, and you can access the fields of that first record per index (0-based).
The result of your count(*)-query is always one row with one column, holding the number of records. So you can access the number of rows with adoRecordset(0) (=first field of first record)
You could create a function to fetch the number of records:
Const strConnect = "..."
Function CountValues(tableName As String) As Long
Dim strSQL As String
strSQL = "SELECT COUNT(*) FROM " & tableName
Dim adoConnection
Dim adoRecordset
On Error GoTo CountValues_ERROR
Set adoConnection = CreateObject("ADODB.Connection")
Set adoRecordset = CreateObject("ADODB.Recordset")
adoConnection.Open strConnect
adoRecordset.ActiveConnection = adoConnection
adoRecordset.Source = strSQL
adoRecordset.Open
Dim res
res = adoRecordset(0)
CountValues = CLng(res)
GoTo CountValues_EXIT
CountValues_ERROR:
MsgBox "An error occurred fetching data: " & Err.Number & " " & Err.Description
CountValues_EXIT:
If adoRecordset.State <> 0 Then adoRecordset.Close
If adoConnection.State <> 0 Then adoConnection.Close
End Function
N.B.: If I where you, I would switch to early binding. Add a reference to the ADODB library and use
Dim adoConnection As ADODB.Connection
Dim adoRecordset As ADODB.RecordSet
Set adoConnection = new ADODB.Connection
Set adoRecordset = new ADODB.RecordSet

How to execute an SQL statement in VBA using " sign to Get the ID with RecordSet Access 2013

I am looking to execute the following code, the problem is, I need to put a String variable in the SQL which should use the "" sign inside the SQL statement.
The problem is, I cannot use multiple "". I tried using Char to use the sign " and convert it to a String, and that's when I got lost.
The code below shows 2 Functions. 1 To see if I get it right to print the correct SQL statement, the other is a Function to return the actual record ID which I will then use to add a new record.
What I mainly looking to do, is use the RecordSet to get a record ID of one of the records.
Any help would be highly appreciated.
Private Sub PrintSQLStatement_Click()
Dim strSQL As String
Dim strTmp As String
Dim i As Integer
strTmp = "UE243"
strSQL = "SELECT tbl_Sales.[ID], tbl_Sales.[SaleReference] FROM tbl_Sales WHERE (((tbl_Sales.[SaleReference])= "" + strTmp + ""));"
i = MsgBox(strSQL, vbOKOnly)
End Sub
Private Function GetSaleID(ByVal strSaleRef As String) As Integer
Dim db As Database
Dim rs As Recordset
Dim strSQL As String
Dim ID As Integer
strSQL = "SELECT tbl_Sales.[ID], tbl_Sales.[SaleReference] FROM tbl_Sales WHERE (((tbl_Sales.[SaleReference])= "" + strSaleRef + ""));"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
ID = rs.GetID
rs.Close
Set rs = Nothing
db.Close
GetSaleID = ID
End Function
You can avoid character escaping issues by using a QueryDef object to run a parameterized query like so:
Private Function GetSaleID(ByVal strSaleRef As String) As Long
Dim db As DAO.Database
Dim qd As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSQL As String
Dim ID As Long
strSQL = _
"PARAMETERS prmSaleRef TEXT(255);" & _
"SELECT tbl_Sales.[ID] FROM tbl_Sales " & _
"WHERE tbl_Sales.[SaleReference]=[prmSaleRef]"
Set db = CurrentDb
Set qd = db.CreateQueryDef("", strSQL)
qd!prmSaleRef = strSaleRef
Set rs = qd.OpenRecordset(dbOpenSnapshot)
ID = rs!ID
rs.Close
Set rs = Nothing
Set qd = Nothing
db.Close
Set db = Nothing
GetSaleID = ID
End Function

MS Access, ComboBox value into SQL statement

The function of my form is to allow a user to assign another user a task, this works fine. The user selects who they want to assign a task to via combo box which is linked to an access DB, I am now trying to implement a feature were by I can get the value of that selected user from the combobox (by matching the ID in the combox to the ID in the DB and then finding the email from that row, so I can then insert it into an outlook email message that pops up on when the user clicks "Assign" (the outlook code works fine it is just not pulling a value from the combo box, so on click it brings outlook new email up, but the "To" field is empty, I have also tried to print the variable I am assigning to that field to ensure it isnt an issue with the outlook code and it stills returns no value).
Here is the section of code that wont work....
Dim OutApp As Object
Dim OutMail As Object
Dim EmailSubject As String
Dim EmailSendTo As String
Dim MailBody As String
Dim db As DAO.Database, rs As DAO.Recordset
Dim s As String
Dim sqlStatement As String
Combo2.SetFocus
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT tblUsers.Email FROM tblUsers WHERE tblUsers.UserID = 'Combo2.Text ")
Combo2 is the name of the combobox
May be so?
Set rs = db.OpenRecordset("SELECT tblUsers.Email FROM tblUsers WHERE tblUsers.UserID = " & Combo2.SelectedItem.ToString())
Try this one:
If your UserID is Text try this one:
Set rs = db.OpenRecordset("SELECT tblUsers.Email FROM tblUsers WHERE tblUsers.UserID = '" & Combo2.Text & "'")
However, if your UserID is numeric try this one:
Set rs = db.OpenRecordset("SELECT tblUsers.Email FROM tblUsers WHERE tblUsers.UserID = " & Combo2.Text)
I don't completely understand how Access comes into play, so if this is wrong I apologize. This is how I would do it in Access:
Dim OutApp As Object
Dim OutMail As Object
Dim EmailSubject As String
Dim EmailSendTo As String
Dim MailBody As String
Dim db As DAO.Database, rs As DAO.Recordset
Dim EmailTo as String
Dim s As String
Dim sqlStatement As String
Combo2.SetFocus
Set db = CurrentDb
EmailTo = DLookup ("Email", "tblUsers", "tblUsers.UserID = '" & Combo2.Text & "'")
If your UserID is an INT, you would change that last line to:
EmailTo = DLookup ("Email", "tblUsers", "tblUsers.UserID = " & Combo2.Text & "")
By the way, you said Edper's solution "didn't pick up anything". You know that "rs" isn't going to have an actual value in that scenario, right? rs("Email") would, however, so if you added:
EmailSendTo = rs("Email")
after his SQL string, that MIGHT give you what you needed.

Data on disk is not directly updated with the 'Update' functionality on my recordset

I am working on some VBA macros. I also use ADODB.Recordset to access data in my Access database.
Now, I need to loop through records in my table and in this loop, also need to update the same table in another function.
Here is the code (cleaned for easy reading).
Dim strSql As String
Dim rstCycles As adodb.Recordset
strSql = "SELECT * FROM tblCycles WHERE DatePlanning = #" & dteCurrentDate & "#"
Set rstCycles = SelectQuery(strSql)
While Not rstCycles.EOF
if ... then
rstCycles("NoCycle1") = ...
rstCycles.Update
end if
RefreshPlanning (*)
rstCycles.MoveNext
Wend
(*) In this function I perform a select on the tblCycles table.
The problem is after the rstCycles.Update, the data is not immediately record on disk thus the call to RefreshPlanning does not read updated data. If I set a '1 second pause' after the update everything is ok. I don't want to use a kind of pause in my loop. Is there another solution?
UPDATE ---------------
RefreshPlanning is a simple function to refresh my excel sheet based on my tblCycles table.
Sub RefreshPlanning(DatePlanning As Date, CodeEquipement As String)
Dim strSql As String
Dim rstCycles As adodb.Recordset
strSql = "SELECT * FROM tblCycles WHERE DatePlanning = #" & DatePlanning & "# AND CodeEquipement = '" & CodeEquipement & "'"
Set rstCycles = SelectQuery(strSql)
While Not rstCycles.EOF
' Some code here to update my excel sheet
' ...
rstCycles.MoveNext
Wend
End Sub
DAO is many times faster than ADO with MS Access:
Dim strSql As String
Dim rstCycles As DAO.Recordset
Dim db As Database
Set db = OpenDatabase("z:\docs\test.accdb")
strSql = "SELECT * FROM tblCycles WHERE DatePlanning = #" & dteCurrentDate & "#"
Set rstCycles = db.OpenRecordset(strSql)
While Not rstCycles.EOF
if ... then
rstCycles.Edit
rstCycles("NoCycle1") = ...
rstCycles.Update
end if
''Need more information here
RefreshPlanning (*)
rstCycles.MoveNext
Wend
If dteCurrentDate is the same as today, you can say:
"SELECT * FROM tblCycles WHERE DatePlanning = Date()"

How do I store the results of my select statement in a variable?

My code so far is this. The last line gives me a compile error: "expected end of statement".
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
groupId = CurrentProject.Connection.Execute strSql
You are looking at something kinda like this
Dim strSql As String
Dim groupId As String
strSql = "Select ID from RevenueGroup where description = '" & ListO.Value & "'"
Dim rec As Recordset
set rec= CurrentProject.Connection.Execute strSql
groupId = rec(0)
You need to set the results of the query to a recordset and then pull the first value from its results. Without all the defined variable, I cannot get this to fully compile but this should be a good template to start from.