I am trying to export a worksheet to Access where it will be paste appended into an existing table. I've referenced this post, this other post, and this other post. I'm getting an error that was not addressed in any of them that I think might be related to VBA libraries but could be something completely different. Here is my code:
Sub ExcelToAccessAdo()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, row As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=filepath\AccessDB.accdb;" 'this is a different filepath from the real one.
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "Table Export", cn, adOpenKeyset, adLockOptimistic, adCmdTable
row = 2 ' the start row in the worksheet
Do While Not IsEmpty(Worksheets("Table Export").Range("A" & row))
With rs
.AddNew ' create a new record
.Fields("REPTNO") = Worksheets("Table Export").Range("A" & row).Value
.Update
End With
row = row + 1
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
The worksheet name and Access table name are the same. Also the .Fields("REPTNO") line is straight from the other person's post so I don't know if I'll have to change it or not.
The error is Run-time error '-2147217900 (80040e14)': Syntax error in FROM clause.
on the line rs.Open "Table Export", cn, adOpenKeyset, adLockOptimistic, adCmdTable.
This is a strange error since it seems like an error I'd get when running SQL, but I'm assuming there's some background SQL happening with an INSERT INTO clause. Which maybe this is some type of file path issue with Excel? Any help?
Here are my library References:
Microsoft Excel 14.0 Object Library
OLE Automation
Microsoft Office 14.0 Object Library
Microsoft Forms 2.0 Object Library
Microsoft ActiveX Data Objects 6.1 Library
Microsoft ActiveX Data Objects Recordset 6.0 Library
Thanks to #JNevill who pointed out I just needed to use square brackets:
rs.Open "[Table Export]", cn, adOpenKeyset, adLockOptimistic, adCmdTable
Try to stay away from spaces in any object name (Tables, Field_Names, Forms, Reports, etc.). You can do this, but as you can tell, it's going to cause more time and unnecessary frustration to normalize things. Also, don't use reserved words in your code.
https://support.microsoft.com/en-us/kb/286335
Related
I have an 'excel front end' for an access database. The idea is that 10 users have their own spreadsheet which can query the database for items relating to them and then they can also respond and write back the database via a macro.
The code is as follows:
Sub update_access()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim cn As ADODB.Connection, rst As ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=S:\Public\XYZ\XYZ\XYZ\XYZ\XYZ.mdb;"
' open a recordset
Set rst = New ADODB.Recordset
rst.Open "qryXYZ", cn, adOpenKeyset, adLockOptimistic, adCmdTable
g = Range("A2").End(xlDown).Row
For f = 3 To g
If Cells(f, 11) <> "" Then
lnId = Cells(f, 1)
rst.Filter = "ID = " & lnId
With rst
.Fields("response") = Cells(f, 11)
.Update
End With
Cells(f, 11).ClearContents
End If
Next f
wb.RefreshAll
MsgBox ("All finished!")
End Sub
It worked perfectly on my own PC whilst I was testing it, however when sending it to the users they all received the same 'project or library not found/missing'
On further investigation and reading I found a post regarding Missing libraries, in my case: Missing: Microsoft Access 16.0 Object Library . Not sure where to go from here, does this mean the users need to have access installed on their PC's to have access to the library or could a copy of my GUID/reference be copied over into their Program Files (x86) (same location as where my reference is)
Starting to get into a realm where I don't want to tread as this would likely mean asking IT department to do that, can anyone think of an alternative solution?
In addition to that I have had to resort to saving the database as .mdb instead of .accdbas "Provider=Microsoft.Jet.OLEDB.4.0; " & _ does anyone know the correct connection type/provider to enable me to access an .accdb as I feel like I've cheated by resorting to an older version of access in order to make my code work?
Hello I am trying to move an Excel worksheet to an Access database, both of which have identical field names. The Code is written in Excel.
The user inputs several form fields and upon clicking finish, a seperate worksheet is updated. Then, the update Access subroutine is called to update the database with the contents of the sheet. However I continue to receive the following error:
Run-time error '-2147417848 (80010108)':
Automation error
The object invoked has disconnected from its clients.
I googled the error and can't quite see what is going on. Here is my code:
Sub Update_Access_fromExcel()
' exports data from the active worksheet to a table in an Access database
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' Connect to Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & "Data Source=D:\Tool_Database\Tool_Database.mdb;"
' open the recordset
Set rs = New ADODB.Recordset
rs.Open "Project_Names", cn, adOpenKeyset, adLockOptimistic, adCmdTable
r = 2
Do Until IsEmpty(Worksheets("NewProj").Cells(r, 1))
With rs
.AddNew
.Fields("Proj_Name") = Worksheets("NewProj").Cells(r, 1).Value
.Update
End With
r = r + 1
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Also, is there a way I could just add the new info to the end of the Access database?
Thanks for your help.
Hey all, have been working on designing a new database for work. They have been using Excel for their daily reports and all the data is stored in there, so I decided to have the back-end of the database in Access and the front-end in Excel, so any analytical work can be easily performed once all the data has been imported into Excel.
Now I'm fairly new to VBA, slowly getting used to using it, have written some code to transfer one of the calculated tables from Access to Excel:
Option Explicit
Public Const DataLocation As String = "C:\Documents and Settings\Alice\Desktop\Database\TestDatabase21.accdb"
Sub Market_Update()
Call ImportFromAccessTable(DataLocation, "Final_Table", Worksheets(2).Range("A5"))
End Sub
Sub ImportFromAccessTable(DBFullName As String, TableName As String, TargetRange As Range)
Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer
Set TargetRange = TargetRange.Cells(1, 1)
' open the database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBFullName & ";"
Set rs = New ADODB.Recordset
With rs
' open the recordset
' .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable
' all records
.Open "SELECT * FROM Final_Table", cn, , , adCmdText
' filter records
For intColIndex = 0 To rs.Fields.count - 1 ' the field names
TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data
End With
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Sub Company_Information()
Dim companyName As String
On Error GoTo gotoError
companyName = Application.InputBox(Prompt:="Enter Company Name", _
Title:="Company Name", Type:=2)
Exit Sub 'Don't execute errorhandler at end of routine
gotoError:
MsgBox "An error has occurred"
End Sub
The above code works fine and pulls up the desired calculated table and places it in the right cells in Excel.
I've got two problems that I'm having trouble with; firstly I have some cell-formatting already done for the cells where the data is going to be pasted into in Excel; I want it to apply the formatting to the values as soon as they are pasted in Excel.
Secondly; I have an add-on for Excel which updates some daily Stock Market values; these values need to be transferred into Access at the end of each working day, to keep the database maintained, I tried some code but have been having some problems with it running.
The code for this part can be seen following:
Sub UPDATE()
Dim cnt As ADODB.Connection
Dim stSQL As String, stCon As String, DataLocation As String
Dim stSQL2 As String
'database path - currently same as this workbook
DataLocation = ThisWorkbook.Path & DataLocation
stCon = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & DataLocation & ";"
'SQL code for GL Insert to Access
stSQL = "INSERT INTO Historical_Stock_Data SELECT * FROM [Portfolio] IN '" _
& ThisWorkbook.FullName & "' 'Excel 8.0;'"
'set connection variable
Set cnt = New ADODB.Connection
'open connection to Access db and run the SQL
With cnt
.Open stCon
.CursorLocation = adUseServer
.Execute (stSQL)
End With
'close connection
cnt.Close
'release object from memory
Set cnt = Nothing
End Sub
I get the following error with this.
Run-time Error '-2147467259 (80004005)'
The Microsoft Jet database engine cannot open the file 'Cocuments and Settings\Alice\Desktop\Database'. It is already opened exclusively by another user or you need permission to view its data.
I'm fairly new to databases, VBA and Access so any help would be greatly appreciated.
Also I have been told that the above method of having an Excel front-end and Access back-end is not recommended but alot of the analysis they conduct is done through Excel, and the charts feature in Excel is much better than Access in my experience atleast; and that is also one of the requirements for this project.
Thank you advance!
Solution to your first problem:
Sorry to be the bearer of bad news, but your entire first module is unnecessary. Instead, try:
Go to Data->Import External Data->Import Data, select your Access file, select your table, and presto! done!
Right-click on your new "External Data Range" to see a number of options, some related to formatting. You can even keep the original cell formatting and just update the values. I do this all the time.
To update the Excel data table later, there is a "External Data Range" toolbar that allows you to refresh it as well as a "refresh all" option to refresh every table in the Excel file. (You can also automate this thru code. It'll take some trial and error, but you're definitely up to the task)
Regarding your second problem
I've never used it, but there is also a "New Web Query" option in there as well. I assume it can be manipulated and updated the same way.
And lastly
Your choice of the Excel front-end and the Access back-end sounds good for your needs. It gets the data to your analysts in a medium they are familiar with (Excel) while keeping the calculations out of the way in Access. Technically, you could try putting all your calculations in Excel, but that might the Excel file much bigger and slower to open.
Do the data entry/updating/reviewing in Access. One of Access' strengths is using forms that allow you to update the tables without any code. Then allow the users to easily export the data to Excel such as by clicking on some command buttons.
Modules: Sample Excel Automation - cell by cell which is slow
Modules: Transferring Records to Excel with Automation
nothing wrong in principle with the excel/access pairing. I'm not familiar with ADO (I use DAO), but your error message seems to be indicating that the path to the datasource is not fully formed; or you already have it opened and hence are locking it.
I am trying to get data from sql server 2005 to excel..
I have written code in excel vba
Below is my code
Dim strConnection, conn, rs, strSQL
strConnection = "Provider=sqloledb;Data Source=LEON7269-G09\SQLEXPRESS;Initial Catalog=test;User Id=sa;Password=sa#123;"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open strConnection
Set rs = Server.CreateObject("ADODB.recordset")
strSQL = "SELECT * FROM UserDetails"
rs.Open strSQL, conn, 3, 3
rs.MoveFirst
While Not rs.EOF
Response.Write (rs("myField") & "<br/>")
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
But i am getting error at line
Set conn = Server.CreateObject("ADODB.Connection")
as runtime error 424
i have tried adding references in vba-->tools-->references
but nothing is working ...Please guide me
If this is Excel VBA, you should get rid of all references to server, that is:
CreateObject("ADODB.Connection")
Not
Server.CreateObject("ADODB.Connection")
This won't work, either:
Response.Write (rs("myField") & "<br/>")
One of the reason for using late binding could be:
Late binding has the advantage that you don not have to compile your code
In case of use in a vba macro, there's no need to set a reference, which make a vba macro harder to deploy
It is said that late binding perform slower because the object-interface is later assigned to the object, hence the expression late binding.
Regards.
You mentioned you have laid a reference then you should have this
Dim conn as Connection
Dim rst as Recordset
Set conn = New Connection
What I'm trying to do is, while in Excel, use VBA to push data to an existing Access table. I've been able to do this, but am having one small hiccup. Before I push the data to access, I want to clear the current data on the Access table, so when the new data from Excel comes in, it is the only data in the Access table. I really don't know how to write code for Access since the class has been on VBA for Excel. I've tried several different approaches and each time it doesn't work. For example, the code that seemed like it should work is
DoCmd.RunSQL "DELETE tblName.* FROM CoversheetTableFourthAttempt
but I get an error telling me to define an object.
If you could help me with this, I would really appricate it
I've put my code below for reference.
Sub AccessFourthMonth()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:\Users\Kent\Documents\MBA\Winter 2009 Semester\MBA 614\Final Project\shilded\testdatabase.mdb"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "CoversheetTableFourthAttempt", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
r = 2 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("Project") = Range("A" & r).Value
.Fields("Description") = Range("B" & r).Value
.Fields("Amount") = Range("C" & r).Value
.Fields("Date") = Range("D" & r).Value
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
Try
DoCmd.RunSQL "DELETE * FROM TableName"
This article might be of interest: Executing SQL Statements in VBA Code
Try the following from Excel:
dim cn as adodb.connection
dim cmd as adodb.command
set cn = new adodb.connection
cn.open "put your connection string here"
set cmd = new adodb.command
cmd.commandtype = adcmdtext
cmd.commandtext = "Delete * from myTable"
cmd.activeconnection = cn.connectionstring
cmd.execute
DoCmd is internal to Access application and not recognized by Excel application.
Simple approach to your problem is to fire the delete query from Excel itself.
Add this part after your cn.Open "Provider.. line
cn.Execute "DELETE * FROM CoversheetTableFourthAttempt"
This should clear the table before next part which fills the data runs.
Your DoCmd approach has two problems. You used a quote to start a string, but didn't include a closing quote. But even with proper quoting, your DoCmd won't work because Excel does not know that CoversheetTableFourthAttempt is the name of a table in an Access database.
You showed that you can successfully create an ADO connection to your Access database. So my suggestion is to use the Execute method of the connection object to execute your SQL statment:
cn.Execute "DELETE FROM CoversheetTableFourthAttempt;"
Finally, visit Problem names and reserved words in Access to understand why Date, Description, and Project are not great choices for Access field names.