MS Access, ComboBox value into SQL statement - sql

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.

Related

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

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) & "'"

Store a single value in variable with SQL Select

I have the following vba code. I am using MS Excel 2013. (I have an insert statement in this code as well, but I didn't copy this just to have a better highlight of my problem)
Dim cn As Object
Dim cUserEmail As String
Dim strSqlmail As String
Dim rss As Object
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ActionList.accdb"
strSqlmail = "SELECT [Email-Adress] FROM MyTable WHERE Name='Test'"
Set rss = cn.Execute(strSqlmail)
cUserEmail = rss.Fields(0).Name
At this point it stores the column name (Email-Adress) in my variable. Running the query in Access returns the column with only my desired value in it.
I think I'm as good as finished, but I cannot seem to find how to get the value. When i change to rss.Field(1) it gives an error saying that the item cannot be found.
If you are using the ADO library then the Execute method returns a RecordSet - see the documentation.
So you need to:
Dim rsResult as Recordset
...
Set rsResult = cn.Execute(strSqlmail)
Do While Not rs.EOF
Debug.Print rs!Email-Adress
rs.MoveNext
Loop
rs.Close
So, when you add your WHERE clause to only return one row, then the loop should only iterate once. Whatever is output to the immediate window is what you should assign to cUserEmail.
The following code gave me the requested value:
Dim cn As Object
Dim cUserEmail As String
Dim strSqlmail As String
Dim rss As Object
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\ActionList.accdb"
strSqlmail = "SELECT [Email-Adress] FROM MyTable WHERE MyTable.[Name]='Test'"
Set rss = cn.Execute(strSqlmail)
cUserEmail = rss.Fields(0)

Access 2013 run time error 3061, Too few parameters. Expected 1 and other oddities

I've begun developing a reasonably simple access project. The DB and queries were built via the app and I have some code which would run through a table and populate another table based on content. This worked fine until I added an additional field (AsOfDate) to one of the tables and I now get the 3061 error when querying the table. If I remove the new field from the SQL it works fine.
So I've looked at the table object when debugging - can't see the new field and also noticed that another Query I setup doesn't get enumerated either.
Is there something I'm missing here in regard to what I'm doing in the front end app versus what I need to do in the VBA ?
The code is simple (so far) but I'll include it hear for reference.
Public Sub PopulateBillingRecords()
'Quick and dirty attempt to replicate desk billing
Dim wrkSpace As Workspace
Dim dbThisDB As DAO.Database
Dim tblUsers As TableDef
Dim tblPermissions As TableDef
Dim tblTrades As TableDef
Dim tblBilling As TableDef
Dim rsUsers As Recordset
Dim rsPermissions As Recordset
Dim rsTrades As Recordset
Dim rsBilling As DAO.Recordset
Dim qryBilling As DAO.QueryDef
Dim strBillingSQL As String
Dim qryUsers As QueryDef
Dim strUsersSQL As String
Dim rowUser As Variant
Dim datAsOfDate As Date
Dim qryTemp As QueryDef
Dim fldThisField As Field
Dim flsAllFields As Fields
Dim strTempField As String
Set wrkSpace = CreateWorkspace("GVUsers", "admin", "", dbUseJet)
Set dbThisDB = wrkSpace.OpenDatabase("GV User Analysis.accdb")
Set tblUsers = dbThisDB.TableDefs("Users")
Set tblPermissions = dbThisDB.TableDefs("MarketPermissions")
Set tblTrades = dbThisDB.TableDefs("Trades")
Set tblBilling = dbThisDB.TableDefs("Billing")
tblBilling.Fields.Refresh
dbThisDB.TableDefs.Refresh
datAsOfDate = Date
'Assuming existing tables populate by import *code import routine later*
'Clear out any existing billing records 'in future allow data to persist and prompt to either clear down data for current billing period if it exists or append
Set rsBilling = Nothing
strBillingSQL = "SELECT Billing.ID, Billing.CompanyCode, Billing.CompanyName, Billing.TraderName, Billing.TraderID, Billing.ConnectionType," _
& "Billing.IsDisabled, Billing.SetupDate, Billing.TPLogCount, Billing.HasConcession, Billing.IsBillable, Billing.BillingPeriod, Billing.DeskByOrdersTrades," _
& "Billing.DeskByPermissions, Billing.OverallDeskAllocation, Billing.HasGasPermissions, Billing.HasPowerPermissions, Billing.HasCoalPermissions, Billing.TradesCount," _
& "Billing.OrdersCount, Billing.AllocationGas, Billing.AllocationPower, Billing.AllocationCoal, Billing.AllocationMethod,Billing.AsOfDate" _
& " FROM Billing;"
Set rsBilling = dbThisDB.OpenRecordset(strBillingSQL, dbOpenDynaset) '<---- 3061 error is returned here
I'm going nuts trying to work out what's going on and think that starting over isn't the solution!
Thanks in advance
It can be cut down to this:
Dim wrkSpace As Workspace
Dim dbThisDB As DAO.Database
Dim rsBilling As DAO.Recordset
Dim strBillingSQL As String
Set wrkSpace = CreateWorkspace("GVUsers", "admin", "", dbUseJet)
Set dbThisDB = wrkSpace.OpenDatabase("GV User Analysis.accdb")
strBillingSQL = "SELECT Billing.ID, Billing.CompanyCode, Billing.CompanyName, Billing.TraderName, Billing.TraderID, Billing.ConnectionType," _
& "Billing.IsDisabled, Billing.SetupDate, Billing.TPLogCount, Billing.HasConcession, Billing.IsBillable, Billing.BillingPeriod, Billing.DeskByOrdersTrades," _
& "Billing.DeskByPermissions, Billing.OverallDeskAllocation, Billing.HasGasPermissions, Billing.HasPowerPermissions, Billing.HasCoalPermissions, Billing.TradesCount," _
& "Billing.OrdersCount, Billing.AllocationGas, Billing.AllocationPower, Billing.AllocationCoal, Billing.AllocationMethod,Billing.AsOfDate" _
& " FROM Billing;"
Set rsBilling = dbThisDB.OpenRecordset(strBillingSQL, dbOpenDynaset) '<---- 3061 error is returned here
That error indicates, that a field in strBillingSQL is misspelled or does not exist in the table.

Retrieve value from Access table in Excel

I have an Excel file that exports data into Word. It includes a cover page and grabs the user name ("First.Last") and changes it to "First Last" but I also need to include the user's professional title. This information is housed in an Access table. It has a field called Name and a field called Title. The Name field match exactly to User with no duplicates.
I have tried about eight different methods I've found online to grab this value from the table. The table will never happen to be open so I can't use "CurrentDB()".
I just need to be able to reach into the table in a database, grab the "title" value given that the value of the field "Name" is equal to the value of User (user name from the environment - the person using the excel file).
If it helps, I can provide examples of the different chunks of code I've used so far.
User is the username from the environment
tblPickName is the table I am trying to open
Path is the directory and file where the table is located
tblPickName has 2 fields, Name and Title
I need to grab the Title from this table and set it to my variable "Title" as long as Name equals User. Then I can export the username and title to Word along with the rest of the data.
Dim Path As String
Dim User As String
Dim Title As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
User = Environ("UserName")
User = Replace(User, ".", " ")
User = StrConv(User, vbProperCase)
Path = "Directory\Name.mdb"
Set db = DBEngine.OpenDatabase(Path)
Set rs = db.OpenRecordset("SELECT tblPickAnalyst.Title FROM tblPickAnalyst WHERE [Analyst]='" & User & "'")
Title = rs!Title
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
docWord.Bookmarks("AnalystName").Range.Text = User
docWord.Bookmarks("AnalystTitle").Range.Text = Title
Try this:
Public Sub JohnTayloristheBest()
Dim conAccess As ADODB.Connection
Set conAccess = New ADODB.Connection
Dim rdsAccess As ADODB.Recordset
Dim strTitle as String
With conAccess
.ConnectionString = "Data Source= **insert filepath here** "
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open
End With
With rdsAccess
.Open "SELECT tblPickName.Title FROM tblPickName WHERE tblPickName.Name = '" & Environ("username") & "';", conAccess
If Not .EOF And Not IsNull(.fields(0)) Then
strTitle = .fields(0)
Else
Msgbox "Error: No record in the database for " & Environ("username")
End If
.Close
End With
conAccess.Close: conAccess = Nothing
End Sub
Be sure to select the correct references by doing this: http://msdn.microsoft.com/en-us/library/windows/desktop/ms677497(v=vs.85).aspx
Also, this is my first answer ever written on this site (or any other for that matter), so be kind.
Try this:
Public Function getTitle(name As String)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = DBEngine.OpenDatabase("E:\Temp\Database.mdb")
Set rs = db.OpenRecordset("SELECT Title FROM tblPickName WHERE Name='" & name & "'")
If rs.RecordCount > 0 Then
getTitle = rs!Title
End If
rs.Close
db.Close
End Function
Ensure read access on table tblPickName (for Administrator)
Here is the final solution. Thank you to everyone who helped!
Dim Path As String
Dim User As String
Dim Title As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
User = Environ("UserName")
User = Replace(User, ".", " ")
User = StrConv(User, vbProperCase)
Path = "Directory\FileName"
Set db = DBEngine.OpenDatabase(Path)
Set rs = db.OpenRecordset("SELECT tblPickAnalyst.Title FROM tblPickAnalyst WHERE [Analyst]='" & User & "'")
Title = rs!Title
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
docWord.Bookmarks("AnalystName").Range.Text = User
docWord.Bookmarks("AnalystTitle").Range.Text = Title

VBA Select Query into String for use with automatic population of web page form

I am trying to:
Run a select query on an Access DB using VBA (this part is simple), populate a string with the results of the query (one field, but n results) with each result separated by a carriage return.
it's going to be a list of order numbers e.g:
1234567
2345678
3456789
9876543
etc
I then open a web site, wait for it to load, then 'paste' in the string results. Then press a search button (I actually have this part working).
What I can't figure out is how to get the results of the SQL query into a string.
Right now I have them in a Variant and I can't use that with my web site paste and it won't convert into a string using Cstr.
Dim IE As Object
Dim OrderNos As DAO.Recordset
Dim dbs As DAO.Database
Dim strSQL As String
Dim OrderArray As Variant
Dim OrderString As String
'set up the SQL query in easy to swallow lumps.
strSQL = "SELECT [Short Term Storage].[Order no]"
strSQL = strSQL & "FROM [Short Term Storage]"
strSQL = strSQL & "WHERE (([Short Term Storage].[Sales Rep Name] Is Null And [Short Term Storage].[Status]<>'SHIPPED'));"
'set the variable to the results from SQL query
Set dbs = CurrentDb
Set OrderNos = dbs.OpenRecordset(strSQL)
OrderArray = OrderNos.GetRows()
I think I either need to use a For Each loop or a Do Until EOF loop.
How can I get each row of the array into a string, then add a vbcrlf, then the next row of the array until EOF?
I think you need something like:
Dim rs As DAO.Recordset
Set rs = dbs.OpenRecordset(strSQL)
Do Until rs.EOF = True
OrderString = OrderString & rs!FieldName & vbCrLf
rs.MoveNext
Loop