VBA Excel to Access "Syntax error in From clause" - sql

I am using Windows 10, Office 2021. I am trying to get data from a access table name User.
Application.ScreenUpdating = False
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim rfield As ADODB.Field
Dim accdbfile As String
Dim qry As String, i As Integer
Dim n As Long
Dim cnnstr As String
cnnstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\excel work\shareholder.accdb;"
Set conn = New ADODB.Connection
Set rst = New ADODB.Recordset
conn.ConnectionString = cnnstr
conn.Open
qry = "SELECT Login,Pwd FROM user;"
With rst
.ActiveConnection = conn
.Source = qry
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
End With
**For Each rfield In rst.Fields**
ActiveCell.Value = rfield.Name
ActiveCell.Offset(0, 1).Select
Next
Range("A1").Select
Range("A2").CopyFromRecordset rst
rst.Close
Set rst = Nothing
conn.Close
Set conn = Nothing
Getting an error "Syntax error in From Clause". on ** marked line.

Related

Import MDB Table into EXCEL via vba - Need field names/headers

I have this bit of code that I found online that will import access records into excel. strFilePath is the filepath for the MDB and strTableName is the table name I am looking to import
Sub importAccessdata()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sQRY As String
Dim strFilePath As String
strFilePath = Sheets("Setup").Range("C2").Value
strTableName = Sheets("Setup").Range("C4").Value
Set cnn = New ADODB.Connection
Set rs = New ADODB.Recordset
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFilePath & ";"
sQRY = "SELECT * FROM " & strTableName & ""
rs.CursorLocation = adUseClient
rs.Open sQRY, cnn, adOpenStatic, adLockReadOnly
Application.ScreenUpdating = False
Sheet3.Range("A1").CopyFromRecordset rs
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
All of the records import very fast however I cannot get the field names to populate with them! Is there a simple modification I can do to carry the field names with the data?
This is what I use-
Private Sub PullSummaryData()
Const strDb As String = "C:\db\AccessDatabase.accdb"
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim i As Integer
Sheets("Summary").Select
Const strQry As String = "SELECT * FROM [AccessDataTable]"
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDb & ";"
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Open strQry
End With
With Sheets("Summary")
For i = 1 To rs.Fields.Count
.Cells(2,i).Value = rs.Fields(i-1).Name 'fields is a 0 based collection
Next i
.Range("A3").CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub

run-time error '3704' operation is not allowed when the object is closed

Noob here. This vba code in excel is supposed to connect to sql 2008 using ADO, run the query and populate sheet1 in excel. Now, the heading error keeps popping up On this line
" Sheet1.Range("A1").CopyFromRecordset rst".
Sub Code1()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim SqlQuery As String
Application.ScreenUpdating = False
Const stADO As String = "Provider=SQLOLEDB.1;Password=NOPWDHERE;Persist Security Info=True;User ID=sa;Initial Catalog=StockControl;Data Source= PCSMIS01"
Set wbBook = ActiveWorkbook
Set WsSheet = wbBook.Worksheets(1)
SqlQuery = " SELECT * FROm dbo.Site "
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
With cnt
.CursorLocation = adUseClient
.Open stADO
.CommandTimeout = 0
Set rst = .Execute(SqlQuery)
End With
Sheet1.Range("A1").CopyFromRecordset rst
'With rst
' .ActiveConnection = cnt
' .Open SqlQuery
' Sheet1.Range("A1").CopyFromRecordset rst
' .Close
'End With
rst.Close
cnt.Close
Set rst = Nothing
Set cnt = Nothing
End Sub
I have also tried an alternative by using the piece of commented code to copy the data into the sheet.I have researched similar topics on the internet to the best of my ability, but i am more confused now. Please help.
Replace Sheet1 (it isn't referenced) by WsSheet :
Sub Code1()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim SqlQuery As String
Application.ScreenUpdating = False
Const stADO As String = "Provider=SQLOLEDB.1;Password=NOPWDHERE;Persist Security Info=True;User ID=sa;Initial Catalog=StockControl;Data Source= PCSMIS01"
Set wbBook = ActiveWorkbook
Set WsSheet = wbBook.Worksheets(1)
SqlQuery = " SELECT * FROm dbo.Site "
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
With cnt
.CursorLocation = adUseClient
.Open stADO
.CommandTimeout = 0
Set rst = .Execute(SqlQuery)
End With
WsSheet.Range("A1").CopyFromRecordset rst
'With rst
' .ActiveConnection = cnt
' .Open SqlQuery
' Sheet1.Range("A1").CopyFromRecordset rst
' .Close
'End With

"Object Required" error

I have an SQL query that I'm running out of Excel. The objective is to run the query and paste the data into a designated location:
Public Function Pull_SQL_Data()
''''On Error GoTo Err:
Worksheets("Data").Select
Range("B7").Select
Do Until ActiveCell = ""
ActiveCell.Offset(1).Select
Loop
Range("B:S", ActiveCell.Offset(-1, 3)).ClearContents
Worksheets("Data").Select
Range("B7").Select
Dim cnPubs As New ADODB.Connection
Dim strConn As String
Dim rstRecordsets As New ADODB.Recordset
Dim intColIndex As Integer
Dim strSQL As Variant
Application.ScreenUpdating = False
Application.Cursor = xlWait
Set cnPubs = New ADODB.Connection
Set rsPubs = New ADODB.Recordset
Set outCell = Sheets("Data").Range("B7")
strSQL = Sheets("SQL").Range("G1")
strConn = "PROVIDER=SQLOLEDB;"
cnPubs.CommandTimeout = 240
strConn = strConn & "DATA SOURCE=CFS-Serversql;INITIAL CATALOG=UserAnalysis;"
strConn = strConn & "INTEGRATED SECURITY=sspi;"
cnPubs.Open strConn
With rsPubs
.ActiveConnection = cnPubs
.Open strSQL, cnPubs, adOpenStatic, adLockReadOnly, adCmdText
Sheets("Data").Range("B7:S500").ClearContents
Sheets("Data").Range("B4").CopyFromRecordset rsPubs
End With
rsPubs.Close
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
Application.Cursor = xlDefault
Exit Function
Err:
MsgBox "The following error has occured-" & vbCrLf & vbCrLf & VBA.Error, vbCritical, "SQL Connection"
MsgBox VBA.Err
Application.Cursor = xlDefault
Worksheets("DWH").Select
Range("A1").Select
End Function
When run I get:
The following error has occurred- Object required" Error code 424.
Why am I experiencing this issue?
Does this work?
Public Function Pull_SQL_Data()
Dim ws As Worksheet
Dim cnPubs As ADODB.Connection
Dim rsPubs As ADODB.Recordset
Dim strConn As String
Dim strSQL As Variant
Set ws = Worksheets("Data")
Set cnPubs = New ADODB.Connection
Set rsPubs = New ADODB.Recordset
strSQL = Sheets("SQL").Range("G1").Value
strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=CFS-Serversql;" & _
"INITIAL CATALOG=UserAnalysis;INTEGRATED SECURITY=sspi;"
cnPubs.Open strConn
rsPubs.Open strSQL, cnPubs, adOpenStatic, adLockReadOnly, adCmdText
ws.Range("B7:S500").ClearContents
If Not rsPubs.EOF Then
ws.Range("B4").CopyFromRecordset rsPubs
Else
MsgBox "No records were returned!"
End If
rsPubs.Close
cnPubs.Close
End Function

Create a RecordSet Object to output query results into Excel cells

I am working on quering a database on a remote server and have my results in the excel spreadsheet. Say in Column A.
For that reason, I have created a button to allow for an 'at will' action and start setting up my ADODB objects.
The connection to the database is fine, however it is very unclear to me how to set up the .Recordset object (MyOutput) to output the results of my query in Column A. Here is my code:
Private Sub RunQuery_Click()
Dim MyOutput As ADODB.Recordset
Dim cnn As New ADODB.Connection
Dim myCommand As ADODB.Command
Dim stringSQL As String
Dim stringConn As String
cnn.Provider = "Microsoft.Jet.OLEDB.4.0;"
cnn.Properties("Jet OLEDB:System database") = "My path"
stringConn = "Data Source=\'my path';User Id='';Password='';"
cnn.Open stringConn
Set myCommand = New ADODB.Command
myCommand.ActiveConnection = cnn
stringSQL = " My query"
myCommand.CommandText = stringSQL
myCommand.Execute
cnn.Close
Set cnn = Nothing
End Sub
May I have some help here?
Thank you very much for your time guys!
You can use something like the below to do it:
Public Sub RunQuery_Click()
Dim oDB As ADODB.Connection
Dim oCM As ADODB.Command
Dim oRS As ADODB.Recordset
Dim strConn As String
Set oDB = New ADODB.connectoin
With oDB
.Provider = "Microsoft.Jet.OLEDB.4.0;"
.Properties("Jet OLEDB:System database") = "My path"
strConn = "Data Source=\'my path';User Id='';Password='';"
.Open strConn
End With
Set oCM = New ADODB.Command
With oCM
.ActiveConnection = oDB
.CommandText = "My Query"
.CommandType = adCmdText
Set oRS = .Execute
End With
Sheets(1).Range("A1").CopyFromRecordset oRS
oRS.Close
Set oRS = Nothing
oDB.Close
Set oDB = Nothing
End Sub
Alternativly, if you wish to return the field names as well, you could use:
Public Sub RunQuery_Click()
Dim oDB As ADODB.Connection
Dim oCM As ADODB.Command
Dim oRS As ADODB.Recordset
Dim strConn As String
Dim iCols As Long
Set oDB = New ADODB.connectoin
With oDB
.Provider = "Microsoft.Jet.OLEDB.4.0;"
.Properties("Jet OLEDB:System database") = "My path"
strConn = "Data Source=\'my path';User Id='';Password='';"
.Open strConn
End With
Set oCM = New ADODB.Command
With oCM
.ActiveConnection = oDB
.CommandText = "My Query"
.CommandType = adCmdText
Set oRS = .Execute
End With
For iCols = 0 To oRS.Fields.Count - 1
Sheet(1).Cells(1, iCols + 1).Value = oRS.Fields(iCols).Name
Next
Sheets(1).Range("A2").CopyFromRecordset oRS
oRS.Close
Set oRS = Nothing
oDB.Close
Set oDB = Nothing

VBA Set Recordset in a report has error This feature is only available in an ADP

I want to set the recordset of an report in access but i get error "this feature is only available in an ADP?
Dim qry As String
qry = "select * from templistdecssched"
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
.ConnectionString = GetConnectionString()
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
With rs
Set rs.ActiveConnection = cn
.Source = qry
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
How can I fix this issue? I am using MS ACCESS 2013