VBA Using SELECT to retrieve data from Access Database - excel

I have issues with a simple "SELECT" query that is coded as the following in Excel using VBA -
CommodityInfo = ObjAccess.CurrentProject.Connection.Execute( _
"SELECT TOP 1 Commodity FROM [" & CustomerName & "]")
It works fine. But then what I'm struggling with is using the information provided to me within the CommodityInfo variable. I can see in my Locals window that the information is there to be accessed I just wouldn't know how to use it to output the value.
Item 1 is clearly displayed so its being accessed. How do I pull out the value information from item 1 and use it as I would a string..?
Count can be used by simply stating CommodityInfo.Count, I tried doing something like ComVal = CommodityInfo(1).Value but I get the error 'Item cannot be found in the collection corresponding to the requested name or ordinal'.
Any help would be appreciated.

As noted in comments, your code is opening a recordset object, not pulling a single value.
Since field index is zero based, use 0 for first field instead of 1: ComVal = CommodityInfo(0) to pull single field value from recordset to simple variable.
Or append Execute command with field index reference to extract single field value directly to simple variable.
CommodityInfo = ObjAccess.CurrentProject.Connection.Execute( _
"SELECT TOP 1 Commodity FROM [" & CustomerName & "]")(0)
Here is alternative to pull a single value instead of opening a recordset:
CommodityInfo = ObjAccess.DLookup("Commodity", "[" & CustomerName & "]").
In my test, it ran faster.
It is possible to pull data from Access without instantiating an Access application object variable. I found this code ran fastest.
Dim cn As New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='your access database filepath'"
CommodityInfo = cn.Execute("SELECT TOP 1 Commodity FROM [" & CustomerName & "]")(0)
Or
Dim cn As New ADODB.Connection
cn.Open "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & ThisWorkbook.FullName & ";HDR=Yes';"
CommodityInfo = cn.Execute("SELECT TOP 1 Commodity FROM [" & CustomerName & "]" IN 'your database filepath'")(0)

Related

The INSERT INTO statement contains an unknown field name

I'm using the following code to export information from an excel file to an access database. It worked fine last time I used it but ever since I started it up today I've been running into the following issue.
Public Sub Export_to_ACCDB()
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\Newdatabase.accdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.Worksheets("DATABASE").Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
'ssql = "INSERT INTO Database ([Column1],[Column2],[Column3]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql '<<< The error occurs here
End Sub
I get the following error running this code:
Run-time error '-2147217900 (80040e14)':
The INSERT INTO statement contains the following unknown field name: 'F12'. Make sure you have typed the name correctly, and try the operation again.
I don't have a field name called 'F12' in either my excel file or my access database. I can't seem to figure out what's going on.
Column headers are written correctly.
Column headers do not contain spaces or other irregularities.
EDIT:
Seems like Excel thinks you got a 12th column (maybe by accidentally entering something). Mark column L and delete it #FunThomas
This seemed to be the problem. I had to delete all the columns after the last one which contained the correct fieldname. Now it's working again.

Execute sql complex query through excel vba

Just to give you background of my work, i have to fetch data from MS Sql on daily basis and for that every time have to go to other server to run the query. Once the query is executed, have to paste into my common drive, which takes a lot time. ~55 mins to paste 5,00,000 row & 30 fields to common or to move file. In total 2 hours for execution & movement from one location to other.
To reduce this i would need your help to use the SQL queries through excel with the below things:
If possible,
Point1: Query will be stored in the text file in the common location
Point2: Query Parameter to be populate to get
Or
Point2:Range to be defined for parameter
If not possible above,
Query will be pasted into the code and parameter to be populated based on the above mentioned suggestion.
Connection type is windows authentication, it will work based on logged in users windows name.
This code will allow you to provide variables that you use within your SQL statement and put those into cells on a spreadsheet (In this case Cred2) and return the results on a separate sheet (Sheet2).
The first portion of the code establishes a connection with the SQL server.
The column Headers will be started in Row 2 and then the data will begin populating starting on row 3. I have used this to pull well over 100,000 records at a time and this works very quickly.
Private Sub CommandButton1_Click()
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL As String
strCon = "DRIVER=SQL Server;SERVER=ServerName;DATABASE=DBName;Trusted_Connection=True"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
' if not a trusted connection you could replace top line of strCon with
strCon = "DRIVER=SQL Server; Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword"
' set up where you are getting your variables to include in the SQL statement
stat = Sheets("Cred2").Range("c7").Value
barg = Sheets("Cred2").Range("c10").Value
worksite = Sheets("Cred2").Range("c11").Value
' Construct SQL statement
strSQL = "select * " _
& " FROM tableName A , table2 B " _
& "WHERE A.[field1] = B.[field1] " _
& " and field1 like '" & stat & "'" _
& "and field2 like '" & barg & "'" _
& "and field3 like '" & worksite & "'" _
& " order by Field? "
' Build Record Set
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open strSQL
' Display Data
For intColIndex = 0 To rs.Fields.Count - 1
Sheet2.Range("A2").Offset(0, intColIndex).Value = rs.Fields(intColIndex).name
Next
Sheet2.Range("A3").CopyFromRecordset rs
' Close Database
rs.Close
cn.Close
Set cn = Nothing
end sub

VBA obtaining a SUM of values from MS Access, returns error: No Value Given For One or More Parameter

I have the following code to retrieve a sum out of an access field.
keep getting the error "No Value Given For One or More Parameter". I'm assuming its something simple. I tried looking up the syntax and google appears to give me what i already have. Appreciate your help.
EDIT
Public Sub sum()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim countfrmdb As String
Dim currentmth As String
currentmth = Sheets("Data").Range("f3") 'this has been formatted to get the month name. e.g: Jan. Thats how its in my database.
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=data.mdb"
strSql = "SELECT SUM(field_name) As Total FROM Table_name WHERE field_month_name = " & currentmth
cn.Open strConnection
Set rs = cn.Execute(strSql)
countfrmdb = rs.Fields(0)
MsgBox (countfrmdb)
You indicated currentmth is a text value containing the current month. So when you add currentmth to the WHERE clause without enclosing it in quotes, the db engine thinks Jan is the name of a parameter instead of a text value.
Change this ...
WHERE field_month_name = " & currentmth
to this ...
WHERE field_month_name = '" & currentmth & "'"
A good way to troubleshoot these type of issues is to examine the actual text of the SQL statement you're asking Access to execute. Debug.Print is useful for that purpose.
strSql = "SELECT SUM(field_name) As Total FROM Table_name WHERE field_month_name = " & currentmth
Debug.Print strSql
You can then view the output from Debug.Print in the Immediate window. And you can copy the statement text from there and paste it into SQL View of a new Access query for testing. Or you can show us the actual statement text which is producing the error your reported.
Based off of the information found here: No value given for the required parameter I would say that your Field_Name or table_name aren't correctly spelled. You can test this by purposefully putting in the wrong field name and you will get the same error you are getting.

Updating Data from Access Database from Excel

I would like to have a simple tool built using excel vba to update existing records and also to add new records to an access database. The goal is to use only 2 clicks to complete the action.
First Part - Resolved (Retrieve Data from Access Database): I have created a excel table that queries data from access database in a tab named "Mapping Matrix" , so everytime an update is required, will use a function to refresh the data.
So, I will update the existing data in the Sheet "Mapping Matrix", or even add new data before I will require this data to be propagated into my access database.
Second Part - Please help (Update the access database "Mapping" using the excel spreadsheet tab "Mapping Matrix")
Here is what I have done to try update existing records with that queried in Excel. However I am faced with this error message that says "The INSERT INTO statement contains the following unknown field name: 'F1'. Make sure you have typed the name correctly, and try the operation again."
Do not quite understand how to fix the error, as I have not applied F1 in the code.
Note: I will require this data to replace that in the access database (not adding on to existing data)
Thanks all in advance!
Public Sub Populate_Data()
Set cn = CreateObject("ADODB.Connection")
dbPath = "Access Database Path.mdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
ssql = "INSERT INTO Mapping ([Field1], [Field2], [Field3]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub

update and delete single access record set via excel vba

I have this tool where employee information needs to be updated. I call in the MDB data to excel in one sheet. Now I use vlookup to see what is there and change it if needed.
I have tried some tricks however some thing seems to be wrong.. please help.
Sub update()
Dim cn As Object
Dim rs As Object
Dim a As String
strFile = "D:\temp excel\EIM.mdb"
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
a = Sheet2.Range("D4")
strSQL = "SELECT * FROM EIM WHERE EIM.NBKID=" & a
rs.Open strSQL, cn
strSQL = "UPDATE EIM SET EIM.Person#=('" & Sheet2.Range("D5") & "')WHERE EIM.NBKID=('" & Sheet2.Range("D4")
cn.Execute strSQL
End Sub
In the above code the file EIM has a table called EIM with NBKID and Person# fields.
So sorry about not explaining the request clearly, I have this tool which allows people to update there information. I cannot use access to manipulate it as not all have access available and even it would be available I do not want to give them access to master database.
We have more than 500 employee's when ever some one moves out of one role to another or when someone leaves the organization. A manager has to request for hierarchy report which takes time to come.
Instead of going through that I want this tool to maintain record of all the employees, here nbkid is nothing but system id and person# is employee number or id.
I have a code to update the information however if someone needs to edit it due to some change to their role than I need another set of code.
By doing it in excel it is easy to manage - no additional training.
I have this button which should update the change made to the vaules updated in excel sheet. I dont want it to check if the record change, I just want it to use update.
When I run the above code I get error saying "No value given for one or more reqired parameters."
I agree as to the point of modifying the data in excel as opposed to directly in access however I just spotted that your SQL statement seems to be slightly wrong. Try changing
WHERE EIM.NBKID=('" & Sheet2.Range("D4")
to
WHERE EIM.NBKID=" & Sheet2.Range("D4")
Note the removal of the single quote mark as the original statement would have been seen as
WHERE EIM.NBKID=('123456
You are missing a space between the bracket and where:
strSQL = "UPDATE EIM SET EIM.Person#=('" & Sheet2.Range("D5") _
& "') WHERE EIM.NBKID=('" & Sheet2.Range("D4")
The single quotes are needed if NBKID is a text field:
WHERE EIM.NBKID=('" & Sheet2.Range("D4") & "'"
Or for a numeric field:
WHERE EIM.NBKID=(" & Sheet2.Range("D4")
I doubt that this is a date field, but if it was, it would take hash (#) delimiters.
Just as a point of efficiency, I am not sure why you actually opened the recordset at all. The cn.Execute line works very well by itself.
I would also write a function you could call and pass it parameters to, depending on what you are trying to do. If you passed in the ID, the strFileName and the strSQL, then you have an all-purpose function.
I have a prebaked SQL string somewhere on a key pair "SELECT * from tblFoo WHERE tblFoo.ixFoo = {key}". I then get the parameter and do a Replace on the strSQL to insert the key.
Sub Update(strFile as string, strKey As String, strPerson as string)
Dim cn As Object : Set cn = CreateObject("ADODB.Connection")
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"
cn.Open strCon
strSQL = "UPDATE EIM SET EIM.Person#="{person}" WHERE EIM.NBKID={key}"
strSQL = Replace(strSQL, {person}, strPerson, 1)
strSQL = Replace(strSQL, {key}, strKey, 1)
cn.Execute strSQL
End Sub
If speed of code greater than need for speed of execution (which is what I can gather here), then this approach alleviates all the quote/doublequote confusion
I would set aside a sheet in the book that had all the strSQL statements there, if you had a few. You could even pass this in and do the replace within Excel with its much faster native execution speed.
You now have a function you can pick up and reuse. If you are serious about using VBA, reuse heavily. It saves so much time. VBA jobs tend to place a high amount of pressure on time to produce.
I presume that you have removed error trapping to save us the hassle of reading it.

Resources