VBA openRecordSet - excel

All I want to do is use VBA to get the results of some query into an Excel workbook instead. The main issue is that the openRecordSet method appears to not be working. Every time when I try debugging it I see that the recordset (rcset) is Nothing. When I just run the query so it is viewed in the Access viewer, it seems to work just fine (see last line of code). I get no errors when I run the code, so I'm having a very hard time understanding why my recordset would return Nothing. I've searched around the internet quite a bit, but haven't found anyone in this particular situation. Thanks in advance for any help!
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim rcset As DAO.Recordset
Dim i As Integer
'Identify the database and query
Set db = CurrentDb
On Error Resume Next
With db
.QueryDefs.Delete ("RealQuery")
Set qdef = .CreateQueryDef("RealQuery", strSQLRQ)
.Close
End With
'The problem child line
Set rcset = qdef.OpenRecordset()
'Clear previous contents
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.Workbooks.Add
.Sheets("Sheet1").Select
'Copy the recordset to Excel
.ActiveSheet.Range("A2").CopyFromRecordset rcset
'Add column heading names to spreadsheet
For i = 1 To rcset.Fields.Count
xlApp.ActiveSheet.Cells(1, i).Value = MyRecordset.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "RealQuery", acViewNormal

Option Explicit
Public Const strQry = "insert sql select command here"
Public Const conStr = "insertconnectionstringhere";
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Sub sql2excell()
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open (conStr)
rs.Open strQry, cn
If Not rs.EOF Then
ActiveSheet.Range("A1").CopyFromRecordset rs
End If
rs.Close
cn.Close
End Sub
Simplest SQL to excel vba i can get

Related

Single Result from recordset returning w/o being transposed

I am working on a project where I'm using SQL to return records from a database into a listbox using userinput. Things are fine when there's more than one result, the listbox reads properly. However, when there's only one record, it doesn't transpose it like it does with all the others. Multiple Returns Single Return
I've tried to do an "if employeeoutput.recordcount = 1 then don't transpose" type of thing, but that still sends me with the Single Return.
Private Sub cmdSearch_Click()
Stop
'connect to database
'make dynamic code
'profit
'set up DB and Recordset
Dim calldbconn As ADODB.Connection
Dim EmployeeOutput As ADODB.Recordset
Dim EmpData As Variant
'its a special tool we're going to use later
Dim InContactInput As String
Dim FNameInput As String
Dim LNameInput As String
Dim TeamNameInput As String
Dim TeamNumberInput As Integer
Dim SQLString As String
'set it up for a new recordset
Set calldbconn = New ADODB.Connection
Set EmployeeOutput = New ADODB.Recordset
'set the vars
InContactInput = txtInContactNum.Value
FNameInput = txtFirstName.Value
LNameInput = txtLastName.Value
TeamNameInput = cboTeamName.Value
TeamNumberInput = cboTeamName.ListIndex + 1
'---------A bunch of stuff here to build the SQL String----------
'----------------------------------------------------------------
'Time to connect
calldbconn.ConnectionString = StrCallDB
calldbconn.Open
On Error GoTo CloseConnection
With EmployeeOutput
.ActiveConnection = calldbconn
.Source = SQLString
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
EmpData = .GetRows
On Error GoTo CloseRecordset
End With
'And now, the list box
With lstResults
.Clear
.List = Application.Transpose(EmpData)
End With
'close and reset
CloseRecordset:
EmployeeOutput.Close
CloseConnection:
calldbconn.Close
Set EmployeeOutput = Nothing
Set calldbconn = Nothing
End Sub

Multiple-step OLE DB Operation generated errors. Check each OLE DB Status Value

Please help me. Excel VBA is throwing this error: Multiple-step OLE DB Operation generated errors
on the line : cmd.Parameters("[days]") = ActiveWorkbook.Sheets("MABI_Extracts").Range("B18").Value
I'm trying to run a query in access named "AGBA_Conversion" with an integer parameter. How do I resolve? thanks in advance :)
Sub RECT_MBTCLeads2_Extracts()
Dim cmd As New ADODB.Command, rs As ADODB.Recordset
Dim sht As Worksheet
Dim b As String
Dim d As Long
Dim a As String
Set sht = ActiveWorkbook.Sheets("AGBA_Conversion")
sht.Range("B1").ClearContents
cmd.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\nemberga\OneDrive - AXA\Documents\Automation\MBTC Conversion.accdb"
cmd.CommandType = adCmdText
cmd.CommandText = "AGBA_Conversion" '<<<--here is where you write your query sql
cmd.Parameters("[days]") = ActiveWorkbook.Sheets("MABI_Extracts").Range("B18").Value
Options = adCmdTable
Set rs = cmd.Execute
sht.Range("A1").CopyFromRecordset rs '--bulk copy to the Excel sheet
rs.Close
cmd.ActiveConnection.Close
MsgBox "All data were successfully retrieved from the queries!", vbInformation, "Done"
End Sub
Parameters is a collection of Parameter. You need first to create the object using CreateParameter, then to add it to the collection using Append.
Replace
cmd.Parameters("[days]") = ActiveWorkbook.Sheets("MABI_Extracts").Range("B18").Value
By
Dim p
Set p = cmd.CreateParameter("days", adInteger, adParamInput)
p.Value = ActiveWorkbook.Sheets("MABI_Extracts").Range("B18").Value
cmd.Parameters.Append p
See https://learn.microsoft.com/fr-fr/sql/ado/reference/ado-api/append-and-createparameter-methods-example-vb?view=sql-server-ver15

How to update a chart?

I have a PowerPoint presentation with ~200 slides. Each slide has one chart, with data that is updated monthly by a link to a master xlsx file.
To not show empty values (future months) in the charts, I open the data editor (chart right click > Edit data...) of every chart and select the range until the current month.
I wrote a macro for it in PowerPoint:
Sub Refresh_slides()
For i = 1 To ActivePresentation.Slides.Count
Set ObjSlide = ActivePresentation.Slides(i)
On Error Resume Next
Set mychart = ObjSlide.Shapes("Chart 3").Chart
mychart.Select
mychart.ChartData.Activate
Set wb = mychart.ChartData.Workbook
Set ws = wb.Worksheets(1)
Application.Run "Refresh_slides_AUX.xlsm!atual_slide"
wb.Close True
Next
End Sub
Refresh_slides_AUX.xlsm is an auxiliary macro worksheet to select the correct range of each chart (because PowerPoint VBA, as far as I know, don't have an option to do it):
Sub atual_slide()
Windows("Gráfico no Microsoft PowerPoint").Activate
ActiveSheet.ListObjects("Table1").Resize Range("$A$1:$I$23")
ActiveWindow.Close SaveChanges:=True
End Sub
The result is:
BEFORE:
AFTER:
It works, but after the range is resized the charts don’t change, they still looking like the BEFORE picture.
I know the process is right because if I do the resizing manually (right corner of the dotted line) the chart is updated correctly.
Add wb.Application.Update before wb.Close
See if that helps.
This is an old question but I had trouble finding an answer and this question came up as the first hit for my search.
I'd like to post a powerpoint vba routine that has an ActivateChartDataWindow method that I found was necessary to refresh the chart after I had updated the data.
Private Sub RefreshChart(slideName As String, shapeName As String, spName As String, dataRange As String)
'Add reference to Microsoft ActiveX Data Object 6.x Library
'Read data point info from SQL
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connStr As String
Dim query As String
Dim sld As Slide
Dim shp As Shape
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Set sld = ActivePresentation.Slides(slideName)
Set shp = sld.Shapes(shapeName)
Set xlWB = shp.Chart.ChartData.Workbook
Set xlWS = xlWB.Sheets(1)
xlWS.Range(dataRange).Clear
Set conn = New ADODB.Connection 'CreateObject("adodb.connection")
connStr = "Provider=SQLOLEDB;Data Source='" & SQLServer & "';Initial Catalog=WVCore;Integrated Security=SSPI;"
conn.Open connStr
Set rs = New ADODB.Recordset 'CreateObject("adodb.recordset")
query = "exec " & spName 'usp_WVCRevenue
With rs
.ActiveConnection = conn
.Open query
xlWS.Range("A2").CopyFromRecordset rs 'Leave headings in tact
.Close
End With
shp.Chart.ChartData.ActivateChartDataWindow
xlWB.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
End Sub

I'm closing recordset and dataconnection for my vba created pivot table, still they show up in existing connections

I'm new in creating pivot tables in VBA. I'm curious to why my closed connections don't seem to affect existing connections? Also, I'm not able to refresh the table, I assume it is because VBA closes all connections when the procedure hits the end sub statement.
How can I make my pivot table refreshable and why do the connections always apprear in the existing connections even though they should be closed?
My code
Private Sub PivotAccessADODB()
' Link Pivottable to access database
Const ConnectionPath As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Desktop\DataBase.accdb;Persist Security Info=False;"
Dim DataConnection As ADODB.Connection: Set DataConnection = New ADODB.Connection
Dim RecordSet As ADODB.RecordSet: Set RecordSet = New ADODB.RecordSet
DataConnection.ConnectionString = ConnectionPath
DataConnection.Open
Dim SQLString As String: SQLString = "SELECT * FROM ALFA"
With RecordSet
.ActiveConnection = DataConnection
.Source = SQLString
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
' Initiate accept of external data
Dim PTCache As PivotCache
Set PTCache = ActiveWorkbook.PivotCaches.Create(xlExternal)
Set PTCache.RecordSet = RecordSet
Dim PT As PivotTable: Set PT = PTCache.CreatePivotTable(Worksheets("Pivot").Range("A1"), "Test")
'Cleanup
RecordSet.Close: Set RecordSet = Nothing
DataConnection.Close: Set DataConnection = Nothing
The connection doesn't close because it is referenced, indirectly, by the pivot table. Using an idiom like the one below avoids this problem:
Private Function executeQuery(sqlStatement) As ADODB.recordSet
'where conn is a global ADODB.Connection object
Set executeQuery = conn.Execute(sqlStatement, RecordsAffected:=0)
End Function
Private Sub displayResultsFor(rs As recordSet, target As Range)
writeHeader rs, target
writeBody rs, target
End Sub
Private Sub writeHeader(rs As ADODB.recordSet, target As Range)
Dim header As Range
Dim i As Integer
Set header = target
For i = 0 To rs.Fields.Count - 1
header.value = rs.Fields(i).name
Set header = header.Offset(ColumnOffset:=1)
Next i
End Sub
Private Sub writeBody(rs As ADODB.recordSet, target)
target.Offset(RowOffset:=1).CopyFromRecordset rs
End Sub
This will display the contents of the recordset and avoid the pivottable and thereby avoid the stored connection. This may or may not be what you want. The other option that you have is write a bit of code to delete the connection. The downside of that is that you will no longer be able to use
pt.RefreshTable

Can't populate my OLEObject combobox

I am trying to populate my combobox through an adodb connection and recordset with data from an access database. The code has previously run fine but in a normal userform, my issue is that I can't properly reference to the combobox.additem property.
How do I reference to it when the ActiveX object is directly on the worksheet "Mainwindow"?
The codename of the shape is: CombBox_Instruments
The control code name should be: Forms.ComboBox.1
I have market where I get the error, the current error is: Run time error 1004: Application defined or object defined error
Here is my code
Private Sub Workbook_Open()
Dim DataConnection As ADODB.Connection: Set DataConnection = New ADODB.Connection
Dim RecordSet As ADODB.RecordSet: Set RecordSet = New ADODB.RecordSet
Dim SQLString As String
Const ConnectionPath As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Desktop\Database.accdb;Persist Security Info=False;"
DataConnection.ConnectionString = ConnectionPath
DataConnection.Open
SQLString = "SELECT Name FROM MSysObjects WHERE Type =1 AND Flags=0"
With RecordSet
.ActiveConnection = DataConnection
.Source = SQLString
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
Do Until RecordSet.EOF = True
If RecordSet.Fields(0) <> "Instruments" Then
Debug.Print RecordSet.Fields(0)
Sheets("Mainwindow").OLEObjects("Forms.ComboBox.1").AddItem RecordSet.Fields(0) - ISSUE IS HERE!
RecordSet.MoveNext
Else
RecordSet.MoveNext
End If
Loop
End Sub
Assuming the Combo Box named CombBox_Instruments is on the sheet "Mainwindow" your code should be:
Sheets("Mainwindow").CombBox_Instruments.AddItem RecordSet.Fields(0)

Resources