I'm trying to do a query in an access db and then get this query result and insert into a Excel sheet, but nothing I do work. This is my code
Sub Analise()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sSQL As String
Sheets("Plan1").Range("A2:A23").Select
For Each Regra In Selection
If Regra = "MYRULE" Then
sSQL = "SELECT ITEM !, ITEM2 FROM base WHERE NomeRegra = ""'MyValue'"" "
MyConn = "MyPath\base.mdb"
Set cnn = New ADODB.Connection
With cnn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:=sSQL, ActiveConnection:=cnn, CursorType:=AdForwardOnly, LockType:=adLockOptimistic, Options:=adCmdText
Sheets("Plan1").Range("D1:E1") = Array("Field1", "Field2")
Range("D2:E100000").CopyFromRecordset rst
rst.Close
cnn.Close
End If
Next Regra
Have you tried using MS Query in Excel using your Access file as the DB? From the data tab in Excel,
'Get External Data' 'From Other Sources' dropdown and then 'From MS Query'
Select MS Access Database and then find your file. When the Query Wizard pop up appears, hit cancel and then 'Yes' to continue editing in MS Query. If you'd rather write the SQL yourself, you can press the sql button, but the language is a little different than Access. It might take some playing around, but MS query can be a very powerful tool.
Related
I am using excel workbook as a database (ExcelDB) and connecting to it via ADODB. In a different excel workbook, I have a userform that I am using for data entry. What I am trying to do is to have the value of a textbox and insert it into the column, FirstHeader, in the table in one of the worksheets (WorkSheet1) in ExcelDB. I hope further that any other entry in that textbox will be added to the last row of that table when I click the commandbutton. I have tried most of the way insert query is made but I can't make it work. Here is my code.
Private Sub btn_Save_Click()
On Error Resume Next
Public cnn As New ADODB.Connection
Public rst As New ADODB.Recordset
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Reports.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=YES;FMT=Delimited;IMEX=1;"";"
Dim qry As String
qry = "Select * from [WorkSheet1$]"
rst.Open qry, cnn, adOpenDynamic, adLockOptimistic '?:adOpenKeyset, adLockPessimistic - I dont know if have this code wrong...
If rst.RecordCount = 0 Then
MsgBox "no record"
Else
qry = "Insert into [WorkSheet1$]([FirstHeader]) Values (TextBox.Value)" '... or I have this query wrong
End If
Application.ScreenUpdating = True
rst.Close
cnn.Close
Set rst = Nothing
Set cnt = Nothing
End Sub
What is the proper way to write a query so that the input entered in the textbox will be inserted to the lastrow of the table in the worksheet I connected via adodb in excel? Thanks for the help.
You need to execute your Action query as following:
qry = "Insert into [WorkSheet1$]([FirstHeader]) Values (TextBox.Value)"
cnn.Execute qry
For more details: click here
I need to get data from Access to excel vba, I use ADODB.
My problem is that although the database is relatively small and query results 30-40 records only, the process gets stuck either with the ".open" or with "copyfromrecordset" line and takes 40-50 secs to display the records.
This is my code.
I made some tests with different cursor types and locktypes with no result. The query is working executed directly from access and I have no issue when the connection points locally to my PC. I am on office 365. I referenced the activex data objects 2.8 library.
Sub loadTestDisplay2()
Dim myConnectiom As ADODB.Connection
Dim myRS As ADODB.Recordset
Const conStringNet As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\ourserver-f04\COE-Shared\Data Tool\Access\adsLoadTest.accdb; Persist Security Info=False;"
Dim sql As String
sql = "SELECT * FROM tblLoad where user is Null"
Set myConnection = New ADODB.Connection
Set myRS = New ADODB.Recordset
myConnection.ConnectionString = conStringNet
myConnection.Open
With myRS
.ActiveConnection = conStringNet
.Source = sql
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
Sheets.Add
Range("A2").CopyFromRecordset myRS
myRS.Close
myConnection.Close
End Sub
I only have moderate experience when it comes to EXCEL VBA and ADO. I have two files a task file and a calendar file each of which is on a different database and a different server. I need to determine the number of actual work days associated to the task. So I need to take the timestamp date from the task file, check it against the calendar file to determine how many days in the task are actual working days. I figured out how to open two separate database connections in my VBA Script, but what I cannot figure out is how to combine the two files so I can get a working days count.
Something like this
Select Taskid, count(*)
From TaskFile, Calendar
Where TaskDate >= CalendarDate
And TaskDate <= CalendarDate
And CalendarWorkDay = 1
Group by Taskid
I thought about preloading a worksheet with the calendar data but don't see how the query will work.
Any suggestions or code snippets would be greatly appreciated.
This is a quick and dirty subroutine that will do something like what I suggested in the second comment above. It probably won't work exactly as you need it to right out of the box, but the overall idea is sound. Just realize that every record returned in the first query will generate a new query to the second file/database, so it could get pretty hairy if there are a lot of records.
Sub twoRecordsets()
Dim objConn As ADODB.Connection, objConn2 As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL As String
Dim strConn As String, strconn2 As String
'open first connection
Set objConn = New ADODB.Connection
strConn = "<your 1st connection string>"
objConn.Open strConn
'open second connection
Set objConn2 = New ADODB.Connection
strconn2 = "<your 2nd connection string>"
objConn2.Open strconn2
'first query:
strSQL = "Select Taskid, TaskDate From TaskFile GROUP BY TaskID"
'open first recordset using first query
Set rs = New ADODB.Recordset
rs.Open strSQL, objConn
'Die if there are no records returned
If rs.EOF And rs.BOF Then
Exit Sub
End If
'Loop through recordset
rs.MoveFirst
Do Until rs.EOF
'build a sql statement to do the second bit. might have to monkey with quote marks and date formats depending on DB
strSQL = "SELECT count(*) as recordcount FROM calendar where '" & rs.Fields("TaskDate").Value & "' >= CalendarDate And '" & rs.Fields("TaskDate").Value & "' <= CalendarDate And CalendarWorkDay = 1"
'open recordset
Set rs2 = New ADODB.Recordset
rs2.Open strSQL, objConn2
'Get your answer from the return
heresYourAnswer = rs2.Fields("recordcount").Value
'Iterate to next record in rs
rs.MoveNext
Loop
End Sub
I'm trying to connect excel on a database which has the following query.
SELECT * FROM Products WHERE Order = [Enter Order]
but excel can't seem to find this query. It only shows the actual table and other queries which does not use parameters.
Is there a way to connect excel on a query which uses parameters? I'm using MS-Excel 2007.
Some notes.
"Parameter queries must be created in Microsoft Query."
Customize a parameter query
Use Microsoft Query to retrieve external data
ADODB & VBA
''Ref: Microsoft ActiveX Data Objects x.x Library
Dim cmd As New ADODB.Command
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim prm As ADODB.Parameter
Dim strConn As String
strConn = "Provider = Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=z:\docs\test.accdb"
conn.Open strConn
cmd.ActiveConnection = conn
cmd.CommandText = "Query4"
cmd.CommandType = adCmdStoredProc
Set prm = cmd.CreateParameter("EnterText", adVarWChar, adParamInput, 50)
cmd.Parameters.Append prm
cmd.Parameters("EnterText").Value = ActiveWorkbook.Sheets("Sheet5").[A2]
'Execute the Stored Procedure
Set rs = cmd.Execute
ActiveWorkbook.Sheets("Sheet8").Cells(2, 1).CopyFromRecordset rs
'Close the connection
conn.Close
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.