Retrieve value from Access table in Excel - sql

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

Related

How can I set an Excel Cell Value as the criteria for Access Query?

I am creating a new query in MS Access that updates an existing record based on the "Branch" and "Employee" fields. How can I set the criteria to reference cell values? Say A2 holds the "Branch" ID for Access and B2 holds the value for the "Employee" ID in Access.I want to update my Access "Notes" Field. My query works when running in Excel, but only because I have specified what the "Employee" & "Branch" ID's are. Nothing updates when i run my code below:
Code
Sub modify_record()
Dim ac As Object
Dim branchid As String
Dim employeeid As String
Dim notesF As String
Set ac = CreateObject("Access.Application")
branchid = Sheets("Sheet4").Range("A2")
employeeid = Sheets("Sheet4").Range("B2")
notesF = Sheets("Sheet4").Range("C2")
Dim strDatabasePath As String
strDatabasePath = "C:\Users\johnsmith\OneDrive\pbsbackup.mdb"
With ac
.OpenCurrentDatabase (strDatabasePath)
Dim db As Object
Set db = .CurrentDb
db.Execute "Update_Records"
End With
End Sub
Query in MS Access. Saved as Update_Records
UPDATE pbsmaster SET pbsmaster.notes = "notesF" WHERE
(((pbsmaster.branch)="branchid") AND((pbsmaster.employee)="employeeid"));
Your variables don't magically transfer into the query, just because they have the same name.
You need to specify the parameters in the Access query, and pass them via a DAO.QueryDef object in the Excel VBA code.
Here is an example: https://stackoverflow.com/a/2317225/3820271
Dim qd As Object ' DAO.QueryDef
Set qd = db.QueryDefs("Update_Records")
qd.Parameters("branchid") = branchid
' etc.
qd.Execute
Here is my solution from what I learned from #Andre. I am able to execute my code, I noticed working with Parameters is much quicker than opening a recordset with DAO.
Sub foo()
Dim db As Database
Dim qdf As QueryDef
Set db = OpenDatabase("C:\Users\employee\OneDrive\samplefile.mdb")
Set qdf = db.CreateQueryDef("", _
"PARAMETERS pbsbranch text , pbsnotes text; " & _
"UPDATE pbsmaster SET pbsmaster.notes=[pbsnotes] " & _
"WHERE pbsmaster.branch=[pbsbranch] " & _
"")
qdf!pbsbranch = Sheets("Sheet4").Range("A2")
qdf!pbsnotes = Sheets("Sheet4").Range("C2")
qdf.Execute dbFailOnError
Set qdf = Nothing
Set cdb = Nothing
End Sub

run time error 438 when trying to use Openrecordset results

I have an Access project (in Office 2016) which consist of several tables and forms. Also I've designed a user login method which using it, some users must access specific records that I've tried setting them on form load event by following code. One field of my table tbPrimary is initial File which is of type attachment that some other user fill it with images\Word documents\Excel files etc. When I try fill an attachment control with recordset result I get error 438 while other controls fill properly. (error at: Me.InitialFile = rs![Initial File].) Here's the code:
Public Sub Form_Load()
Dim rs As DAO.Recordset ''Requires reference to Microsoft DAO x.x Library
Dim sSQL As String
Dim strSQL As String
Dim nn As Double
sSQL = "SELECT MIN(tbPrimary.[ID]) As mm FROM tbPrimary WHERE Translator IS NULL"
Set db = CurrentDb
Set rs = db.OpenRecordset(sSQL)
If rs.RecordCount > 0 Then
Me.tbSearch1 = rs!mm
Else
Me.tbSearch1 = "N/A"
End If
nn = CDbl(rs!mm)
strSQL = "SELECT * FROM tbPrimary WHERE ID= " & nn & ""
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
If rs.RecordCount > 0 Then
Me!ID = rs!ID
Me.tbInitial_Name = rs![Initial Name]
Me.length = rs!length
Me.Level1_Menu = rs![level1 Menu]
Me.Level2_Menu = rs![level2 Menu]
Me.Level3_Menu = rs![level3 Menu]
Me.Type = rs![Type]
Me.Description = rs!Description
Me.tbMiningDate = rs![Mining Date]
Me.Created = rs!Created
Me.InitialFile = rs![Initial File]
Else
Me.tbSearch1 = "N/A"
End If
Me.Translator.SetFocus
End Sub
(any solution?
Thanks in advance)
Here is a general approach to adding attachments to an Access DB, I hope it helps.
Option Explicit
Sub ExampleAddAccessAttachment()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsattach As DAO.Recordset
Dim fldattach As DAO.Field
Dim filepath As String
filepath = "SOME FILE PATH HERE"
Set db = CurrentDb
'Open a recordset to the table with the attachment
Set rs = db.OpenRecordset("Select * from SOMETABLENAME")
With rs
.AddNew
'The attachment field is a multipart field, so we can treat as a recordset
Set rsattach = .Fields("TheAttachmentFieldName").Value
'Get the fileData Field, this holds the data
Set fldattach = rsattach.Fields("FileData")
'Add a new record to this recordset, you can add multiple
rsattach.AddNew
'Use the load from file method to add a file to the attachment
fldattach.LoadFromFile (filepath)
'Update the recordset with the attachment
rsattach.Update
'Update the parent table recordset
.Update
End With
End Sub

Using SendObject in Access 2013 VBA, using email in table

I am super new at this and need help. I am trying to send a query as an excel document to specific people contained in a table called "tblRelationship", the email is in a field called "Email". However, there are more people in this table then I want to send to. There is a third field called "RelationshipType" that I need to set to = Accounting
I have been using this code that I found:
Const stDocName As String = "qryPOAccountingReport"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim stRecipients As String
Set db = CurrentDb()
Set rs = db.OpenRecordset("tblRelationship")
With rs
Do While Not .EOF
stRecipients = stRecipients & ";" & !Email
.MoveNext
Loop
.Close
End With
If Len(stRecipients) > 0 Then
' discard leading ";"
stRecipients = Mid(stRecipients, 2)
DoCmd.SendObject acQuery, stDocName, acFormatXLS, _
stRecipients, , , "Thank You for your purchase"
Else
MsgBox "No recipients to email!"
End If
Set rs = Nothing
Set db = Nothing
And it works great. I just don't understand how to put the "RelationshipType" criteria in there. Can anyone help?
Thank you in advance!
Simply, run a query in your OpenRecrdset() which can take whole tables, stored queries, or SQL Select statements:
Set rs = db.OpenRecordset("SELECT [Email] FROM tblRelationship" _
& " WHERE RelationshipType='Accounting'")

SetFocus is getting ignored - Why?

I have 2 fields - txtTR1_Unit and cmbTR2_Unit. Together, these 2 fields represent the total UNIT.
cmbTR2_Unit has a list of unique values that when selected - txtTR1_Unit automatically gets the related value.
I've created a function called Tier1from2 - that accepts a 'string' and returns the related Tier1 value.
So when I update cmbTR2_Unit in my After_Update event, I'd like to automatically tab to the next field. - Another combo box. I figured that I shouldn't need to set any focus, because it would automatically go to the next field after updating.
txtTR1 gets updated just as expected from my Function, but then it just sits there and won't go to the next field. So I have attempted to 'SetFocus' to the next field after the update.
Still no go. What did I miss??
Private Sub cmbTR2_UNIT_AfterUpdate()
If Len(Me.cmbTR2_UNIT.Value) <> 0 Then
Me.txtTR1_UNIT.Value = Tier1From2(Me.cmbTR2_UNIT.Text)
'cmb_CostCenter.setfocus - 'this doesn't seem necessary - but it doesn't work anyway.
End If
End Sub
As a test I tried removing the function "Tier1From2(Me.cmbTR2_UNIT.text)" simply hard coding the word 'RESULT' in txtTR1_UNIT and it works without a hitch. I know I used to write a more simple function but I haven't touched VBA in awhile - How can I simplify this function:
Private Function Tier1From2(strTier2 As String) As String
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Dim strQry As String
Dim rs As Recordset
Set db = CurrentDb
Set qdf = db.QueryDefs("qUNIT_HUB")
strQry = "SELECT Tier1_Unit, Tier2_Unit " & _
" FROM LTBL_Cost_Collector " & _
" GROUP BY Tier1_Unit, Tier2_Unit " & _
" HAVING (((Tier2_Unit) = '" & strTier2 & "'));"
qdf.SQL = strQry
db.QueryDefs.Refresh
Set rs = db.OpenRecordset(strQry)
Tier1From2 = rs![Tier1_Unit]
Set db = Nothing
Set qdf = Nothing
Set Recordset = Nothing
End Function
It turns out that something in this function was causing the field and form to loose focus. db.QueryDefs.refresh perhaps? The solution was to update my Function as follows
Private Function Tier1From2(strTier2 As String) As String
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
Dim strTier1 As String
Set db = CurrentDb
strSQL = "SELECT Tier1_Unit, Tier2_Unit " & _
" FROM LTBL_Cost_Collector " & _
" GROUP BY Tier1_Unit, Tier2_Unit " & _
" HAVING (((Tier2_Unit) = '" & strTier2 & "'));"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
strTier1 = rs!Tier1_Unit
Set rs = Nothing
Set db = Nothing
Tier1From2 = strTier1
End Function
This worked without a hitch.

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.