Copying data from excel into access with VBA? - vba

Im trying to update an Access database with new code to add to one aggregate list of scan entries. The macro needs to open the access file, copy the range from excel and paste it at the bottom of the database to add to the already existing records. Then save the access .accdb file and then close. Any tips particularly on the copying and pasting data portion?

Use ACE.OLEDB. Create an SQL INSERT STATEMENT. Code would look something like below:
Sub Test()
accessFilePath = "C:\someDB.accdb"
Call ExecuteSQLCmd("INSERT INTO `" & accessFilePath & "`.`Table` (col1,col2,col3) SELECT col1,col2,col3 FROM [Sheet1$]", accessFilePath)
End Sub
Sub ExecuteSQLCmd(cmd As String, accessFilePath as String )
Dim cnn As ADODB.Connection
Dim sql As String
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFilePath & ";Persist Security Info=False;"
If Not (cnn Is Nothing) Then
'Execute Sql
cnn.Execute (cmd)
'Close
cnn.Close
End If
Set cnn = Nothing
End Sub

Related

Trying to update Excel-Table through Access-VBA Code. Error: Cannot find database Object "Ware"

I have a number of Excel-Files that contain data which I need to combine into one table.
Is it possible and reasonable to do this from within Access VBA code, which I would prefer? Or should I just do it in Excel VBA?
My idea was to iterate through the Excel-Files and use an SQL statement for UPDATE Column WHERE MyCondition, to get the Values I want to the Column I want. Is it possible this way or what would be a suggestion to solving this?
I have tried it this way until now from Access:
Sub Execute_UpdateQuery()
Dim conn As ADODB.Connection
Dim NumOfRec As Integer
Dim strPath As String
strPath = "D:\Sortierliste August_September\Test.xlsx"
Set conn = New ADODB.Connection
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=Excel 12.0 Xml;HDR=YES;"
conn.Execute "UPDATE Ware SET Name = 'test'" & _
" WHERE Name = 'Ackermann'", NumOfRec, adExecuteNoRecords
Debug.Print NumOfRec & " records were updated."
conn.Close
Set conn = Nothing
End Sub
But that results into an error "Cannot find access-database module "Ware". I guess it is because it is just an excel-table and not a database? I thought it can find an excel-file containing the table called Ware and execute an sql query. Any help or suggestions would be great on how to solve this issue.
Greetz

Excel VBA ADO SQL connection error - Could not find the object

I got a brilliant answer to my previous question from #Ryan Wildry but I thought I'd ask a different question regarding the same code: here goes.
Background Info
I have a shared (network/server) Excel template file which is both the input file and the data source (although on different sheets). Let's call that Input.xltm.
The code basically picks up a input in a range on Input Sheet, takes the first two letters and finds the closest code from Code Sheet, then populates a UserForm ListBox with the top five results.
The problem
The problem comes when users set off the UserForm and the error usually returns:
Run-time error '-2147467259'
The Microsoft Access database engine could not find the object 'C:\Users\user.name\Documents\Input1'. Make sure the object exists and that you spell its name and the path name correctly.......etc
I think it may have something to do with the fact Excel puts a number after the filename because it's a template file although I don't actually know!
The code
And here's the code:
Public MyConnection As New ADODB.Connection
Public MyRecordset As New ADODB.Recordset
Private Sub UserForm_Initialize()
Dim ColumnName As String: ColumnName = "[Variant code]"
Dim SearchStr As String: SearchStr = Left(Sheets("Input Sheet").Range("B4").Value2, 2)
Dim dbstring As String
dbstring = ThisWorkbook.FullName
Application.ScreenUpdating = False
If MyConnection.State <> adStateOpen Then
With MyConnection
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbstring & _
";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';"
.Open
End With
End If
If MyRecordset.State = adStateOpen Then MyRecordset.Close
MyRecordset.Open "Select top 5 " & ColumnName & " from [Code Sheet$] where " & ColumnName & _
" like '%" & SearchStr & "%'", MyConnection, adOpenForwardOnly, adLockReadOnly
Me.ListBox1.Clear
If Not MyRecordset.EOF Then MyRecordset.MoveFirst
Application.ScreenUpdating = True
Do Until MyRecordset.EOF
Me.ListBox1.AddItem MyRecordset.Fields(0).Value
MyRecordset.MoveNext
Loop
End Sub
I just need everyone who accesses the file through the server to be able to pick up the correct data source (which is only in the next sheet) and populate the ListBox.
I'd be thankful for any suggestions! Thanks
#UPDATE
I have checked, now if you open (and then save) the actual template file so there's no '1' after the file name, then the code works as expected. It's only when the template is opened normally and the number automatically appended that it stops working.
It seems that you do not make early-binding for MyConnection and MyRecordset first.
You can make a late-binding by
step 1.
Change
Public MyConnection As New ADODB.Connection
Public MyRecordset As New ADODB.Recordset
to
Public MyConnection As object
Public MyRecordset As object
.
step 2.
Add
Set MyConnection = createobject("adodb.connection")
Set MyRecordset = createobject("adodb.recordset")
before If MyConnection.State <> adStateOpen Then

Getting data from an Excel datatable using OLEDB

I have an excel 2007 xlsm file, where on one of the tabs I have several data tables. Using VB.NET, I'm trying to read one table at a time as a named range like so:
Public Function OpeDataFromRange(ByVal Filename as string, ByVal RangeName As String, ByVal bColumnNames As Boolean) as DataTable
' Returns a DataSet containing information from a named range
' in the passed Excel worksheet
Dim sHDR As String
Dim strConn As String
If bColumnNames Then
sHDR = "Yes"
Else
sHDR = "No"
End If
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Filename & ";Extended Properties=""Excel 12.0 Macro;HDR=" & sHDR & """;"
Dim objConn _
As New System.Data.OleDb.OleDbConnection(strConn)
objConn.Open()
' Create objects ready to grab data
Dim objCmd As New System.Data.OleDb.OleDbCommand( _
"SELECT * FROM [" & RangeName & "]", objConn)
Dim objDA As New System.Data.OleDb.OleDbDataAdapter()
objDA.SelectCommand = objCmd
' Fill DataSet
Dim objDS As New System.Data.DataSet()
objDA.Fill(objDS)
' Clean up and return DataSet
objConn.Close()
return objDS
End Function
But I'm getting the error at Fill command:
The Microsoft Office Access database engine could not find the object 'MyNamedTable1'. Make sure the object exists and that you spell its name and the path name correctly.
I tried to read the entire sheet in the SELECT, and then to fish out my table through objDS.Tables, but then Tables gets loaded with only one table with everything in it.
Any Recommendations?
You cannot use Microsoft.Jet.OLEDB.4.0 with Excel 12.0 you should use Microsoft.ACE.OLEDB.12.0 instead.
Incidentally, you are filling a DataSet but returning a DataTable you need to change one of those.
Personally I prefer to use a DataTable for this but you may prefer a DataSet. If you want to use a DataTable you can...
Dim objDT As New DataTable
objDT.Load(objCmd.ExecuteReader)

Error in connecting to Access database from Excel macro

I have to create excel macro which fetches from access database and update appropriate columns in excel worksheet.
I have never done VBA programming before, i am just able to write a code to connect to the database which is giving me error saying "Error in From clause".
Sub Button2_Click()
Dim conn As New Connection
Dim rs As New Recordset
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\Xprts8\Documents\shipping.accdb;" & _
"User Id=admin;Password="
conn.Open (strcon)
qry = "SELECT * FROM shipping-table"
rs.Open qry, conn, adOpenKeyset
rs.Close
conn.Close
End Sub
can anybody help me with the following problem
shipping-table is not a valid table name in an SQL statement (because of the hyphen) unless its escaped thusly:
SELECT * FROM [shipping-table]

Closing an OLE DB connection opened from within a function

Backed myself in a corner....
Used a piece of code I found on the web and can't figure out how to close this connection. The returned OleDbcommand objCommand remains open after processing. I need to it close so I can delete the file after I have pulled the data from it. (Don't want them hanging around on the server.)
This has to be easier than the 100 of lines of code that I have tried to do this. This function opens the connection.
Protected Function ExcelConnection() As OleDbCommand
Dim fileName As String = Session("newUploadedFile")
' Connect to the Excel Spreadsheet
Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
"Extended Properties=Excel 8.0;"
' create your excel connection object using the connection string
Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
' use a SQL Select command to retrieve the data from the Excel Spreadsheet
' the "table name" is the name of the worksheet within the spreadsheet
' in this case, the worksheet name is "Sheet1" and is expressed as: [Sheet1$]
Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", objXConn)
Return objCommand
End Function
I have tried...
ExcelConnection.connection.close()
along with about 40 other attempts to recreate the Command and then close it.
Could really use some help on this one.
This is probably not the best way to do this, but if you really must do it this way consider defining and opening the connection in the calling routine and passing it into this routine as a parameter. It can then be closed in the calling routing, thus...
Sub Main()
Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
"Extended Properties=Excel 8.0;"
Dim objXConn As New OleDbConnection(xConnStr)
objXConn.Open()
Dim ObjCommand As New OleDbCommand = ExcelConnection(objXConn)
'Whatever other operations you want to do with your returned OleDbCommand
...
objXConn.Close()
End Sub
Function ExcelConnection(PassedConnection As OleDbConnection) As OleDbCommand
Dim fileName As String = Session("newUploadedFile")
Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", PassedConnection)
Return objCommand
End Function
I posted something similar to this here... Best fastest way to read an Excel sheet