I lost my working code before I wrote to get data from .mdb file to Excel with VBA. Now, I did not find the true way to get data to excel. Here is the my code to import data;
Sub importAccessdata()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sQRY As String
Dim strFilePath As String
strFilePath = "D:\00 - DENEME\Deneme_Model_v0.mdb"
'Replace the ‘DatabaseFolder’ and ‘myDB.accdb’ with your DB path and DB name
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & strFilePath & ";"
sQRY = "SELECT * FROM Connectivity"
'Replace ‘tblData’ with your Access DB Table name or Query name from which you want to download the data
With rs
.CursorLocation = adUseClient
.Open Source:=sQRY, ActiveConnection:=cnn, CursorType:=adOpenForwardOnly, LockType:=adLockOptimistic, Options:=adCmdText
End With
Application.ScreenUpdating = False
Sheet1.Range(“A1”).CopyFromRecordset rs
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
I got Run-Time Error 424 when I were running to code, I got error in "Sheet1.Range(“A1”).CopyFromRecordset rs" part of code.
I just want to get data from another Software output to use in Excel easily. My .mdb file can be seen here
Whats wrong I don't know. Also I have Sheet1 worksheet in my Excel file.
Related
I have been using the following method to query an MS Access database using Excel VBA for over a decade. All of a sudden yesterday it stopped working. I tried all of the following - reboot, move files to local machine, reinstall Office, a different PC, compact repair database, new database, new excel file, updating reference library (didn't see anything newer), and I've tried several other snippets of code found online.
If i relaunch excel it will work for 1-2 queries then throws the error:
Run-time error '-2147467259 (80004005)':
Unspecified error
It breaks on the line:
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
Here is the code I am running:
Public Function getRS(sSql As String) As Variant
Dim con As ADODB.Connection, rs As ADODB.Recordset
Dim AccessFile As String
Dim Rw As Long, Col As Long, c As Long
Dim MyField, Location As Range
'specify path to db
AccessFile = dbPath 'public variable
'On Error Resume Next
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.Recordset")
'Set thee cursor location.
rs.CursorLocation = 3 'adUseClient on early binding
rs.CursorType = 1 'adOpenKeyset on early binding
'On Error Resume Next
'Open the recordset.
rs.Open sSql, con
Set getRSOLD = rs
Set Location = Nothing
Set con = Nothing
Set rs = Nothing
End Function
I am struggling to find relevant information on the
'run-time error '-2147418113 (8000ffff)' - Catastrophic Failure'
I am experiencing.
Sub GenerateAIA_Click()
Dim SQL_query, SQL_syntax, DB_path, setting_conn As String
Dim conn As New ADODB.Connection
Dim query_rslt As New ADODB.Recordset
Dim mth, mth_yr As Variant
Dim dt As Date
Dim i, bol As Integer
Dim temp1, temp2 As Variant
dt = Sheets("Main").Range("C4")
mth_yr = MonthName(Month(Sheets("Main").Range("I12")), False) & " " & Year(Sheets("Main").Range("I12"))
ThisWorkbook.Sheets("AIA").Select
DB_path = ThisWorkbook.FullName 'Refering the same workbook as Data Source
setting_conn = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DB_path & ";HDR=Yes';"
conn.Open setting_conn
SQL_syntax = "SELECT * FROM [Setup$]" 'Your SQL Statement (Table Name= Sheet Name=[Sheet1$])
query_rslt.Open SQL_syntax, conn
I have also noticed that this error is shown on the line
conn.Open setting_conn
I use excel 2016 and also my file format .xlsm
Anyone have idea why is this happening?
It seems your connection string has a problem.
Here's how I got it to work:
(First make sure to add a reference to the Microsoft Active-X Data Objects Library)
Sub test()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\PC\test.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=NO"";"
conn.Open
rs.Open "SELECT * FROM [Sheet1$]", conn
If Not rs.EOF Then
MsgBox rs(0) ' display the value of the first field in the first row
Else
MsgBox "No records found."
End If
rs.Close
conn.Close
End Sub
So take my example, change the filename to your XLSM file, and the sheet name to your sheet name (with a $ added to the end of it)
If your sheet has header names in the first now, use HDR=Yes, and if not, HDR=No
or you can change display resolution for your monitor
My below code shows no error, when run, but I don't know how to extract required/particular field values into my excel sheet.
Sub getdatafromaccesstoanarray()
Dim cn As Object 'Connection
Dim rs As Object 'Recordset
Dim vAry() As Variant 'Variant Array
Dim dbPath As String 'Database Path
Dim dbName As String 'Database Name
Dim txt As String
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
dbPath = ThisWorkbook.Path & "\"
dbName = "NewDB.accdb"
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & dbPath & dbName & ";"
rs.Open "SELECT * FROM BILLDETAILS WHERE BILLDETAILS.SN_AUTO =100;", cn
vAry = rs.GetRows()
'now when the data is copied to my array how can i paste specific values from this data to
'cells in my excel sheet
'like
'on active sheet
'[a1] = vAry(value1)
'[a2] = vAry(value3)
'[a3] = vAry(value8)
'and other values like wise
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
If there any other way to do this then please let me know.
Thanks!
If you just want to copy the recordset into the sheet you can use the CopyFromRecordset method to dump the table into the sheet by specifying the top left corner:
Range("a1").copyfromrecordset rs
If you want to put specific fields in specific positions you can loop
Do While not rs.eof
range("a2")=rs(0)
range("b2")=rs(1)
'etc....
rs.movenext
Loop
i want to allow the user to upload xls file with 9 columns and unlimited number of rows.
i will run over everyline and insert the data to the db
how do i read the xls file?
You can read the XLS by opening an ADO recordset which pulls in the spreadsheet's data.
This example reads data from a spreadsheet named Billing Summary which includes column names in the first row..
Public Sub ReadSpreadsheet()
Const cstrFolder As String = "C:\Access\webforums"
Const cstrFile As String = "ExampleFinance.xls"
Dim strConnect As String
Dim strSql As String
Dim cn As Object
Dim rs As Object
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
cstrFolder & Chr(92) & cstrFile & _
";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strConnect
strSql = "SELECT * FROM [Billing Summary$] WHERE SomeField Is Not Null;"
rs.Open strSql, cn
Do While Not rs.EOF
'* do something with each row of data *'
'Debug.Print rs!SomeField '
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If that particular connection string doesn't work for you, look at other examples of Excel connection strings at Connection strings for Excel
Edit: That example works in Access. But you said ASP. I think it will work there, too, if you drop the data types from the variable and constant declarations: Dim strSql instead of Dim strSql As String
Example of using an SQL statement to update Access from Excel.
Set cn = CreateObject("ADODB.Connection")
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\docs\dbto.mdb"
cn.Open scn
sSQL = "SELECT * INTO NewTable FROM "
sSQL = sSQL & "[Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\Docs\From.xls].[Sheet1$]"
cn.Execute sSQL, recs
MsgBox recs
In C#, I had to load an excel spreadsheet to a DataSet - this got me there...
Code Project Example
I used Option 1 - the Preferred method! Hope this helps...
Mike
I am working on an Excel application that queries a SQL database. The queries can take a long time to run (20-40 min). If I've miss-coded something it can take a long time to error or reach a break point. I can save the results to a sheet fine, it's when I am working with the record sets that things can blow up.
Is there a way to load the data into a ADODB.Recordset when I'm debugging to skip querying the database (after the first time)?
Would I use something like this?
Query Excel worksheet in MS-Access VBA (using ADODB recordset)
I had to install the MDAC to get the msado15.dll and once I had it I added a reference to it from (on Win7 64bit):
C:\Program Files (x86)\Common Files\System\ado\msado15.dll
Then I created a function to return an ADODB.Recordset object by passing in a sheet name that exists in the currently active workbook. Here's the code for any others if they need it, including a Test() Sub to see if it works:
Public Function RecordSetFromSheet(sheetName As String)
Dim rst As New ADODB.Recordset
Dim cnx As New ADODB.Connection
Dim cmd As New ADODB.Command
'setup the connection
'[HDR=Yes] means the Field names are in the first row
With cnx
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
.Open
End With
'setup the command
Set cmd.ActiveConnection = cnx
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT * FROM [" & sheetName & "$]"
rst.CursorLocation = adUseClient
rst.CursorType = adOpenDynamic
rst.LockType = adLockOptimistic
'open the connection
rst.Open cmd
'disconnect the recordset
Set rst.ActiveConnection = Nothing
'cleanup
If CBool(cmd.State And adStateOpen) = True Then
Set cmd = Nothing
End If
If CBool(cnx.State And adStateOpen) = True Then cnx.Close
Set cnx = Nothing
'"return" the recordset object
Set RecordSetFromSheet = rst
End Function
Public Sub Test()
Dim rstData As ADODB.Recordset
Set rstData = RecordSetFromSheet("Sheet1")
Sheets("Sheet2").Range("A1").CopyFromRecordset rstData
End Sub
The Sheet1 data:
Field1 Field2 Field3
Red A 1
Blue B 2
Green C 3
What should be copied to Sheet2:
Red A 1
Blue B 2
Green C 3
This is saving me a HUGE amount of time from querying against SQL every time I want to make a change and test it out...
--Robert
Easiest would be to use rs.Save "filename" and rs.Open "filename" to serialize client-side recordsets to files.
Another alternative to get a Recordset from a Range would be to create and XMLDocument from the target Range and open the Recordset from that document using the Range.Value() property.
' Creates XML document from the target range and then opens a recordset from the XML doc.
' #ref Microsoft ActiveX Data Objects 6.1 Library
' #ref Microsoft XML, v6.0
Public Function RecordsetFromRange(ByRef target As Range) As Recordset
' Create XML Document from the target range.
Dim doc As MSXML2.DOMDocument
Set doc = New MSXML2.DOMDocument
doc.LoadXML target.Value(xlRangeValueMSPersistXML)
' Open the recordset from the XML Doc.
Set RecordsetFromRange = New ADODB.Recordset
RecordsetFromRange.Open doc
End Function
Make sure to set a reference to both Microsoft ActiveX Data Objects 6.1 Library and Microsoft XML, v6.0 if you want to use the example above. You could also change this function to late binding if so desired.
Example call
' Sample of using `RecordsetFromRange`
' #author Robert Todar <robert#roberttodar.com>
Private Sub testRecordsetFromRange()
' Test call to get rs from Range.
Dim rs As Recordset
Set rs = RecordsetFromRange(Range("A1").CurrentRegion)
' Loop all rows in the recordset
rs.MoveFirst
Do While Not rs.EOF And Not rs.BOF
' Sample if the fields `Name` and `ID` existed in the rs.
' Debug.Print rs.Fields("Name"), rs.Fields("ID")
' Move to the next row in the recordset
rs.MoveNext
Loop
End Sub