The original Excel VBA code retrieved data from MS Access just fine.
I adjusted the connection string, and I am connected to SQL Server 2012, I think, no errors!
however the SQL query does not return any records, and so there must be a trick to writing SQL queries in VBA to return records.
Any suggestions on how to write the query to return field strDISTRICTS from table dbo.DISTRICTS?
Thanks in advance - sportsguy
Here is the code:
Option Explicit
Public Const MyConn As String = _
"Provider=SQLNCLI11;" & _
"SERVER=servername;DATABASE=databasename;" & _
"Trusted_Connection=yes"
Public mySQL As String
Public Cn As ADODB.Connection
Public Rs As ADODB.Recordset
Public Rw As Long
Public Col As Long
Public c As Long
Public MyField As Object
Public Destination As Range
Public OperationID As Range
Public FADescription As Range
Public Sub Retrieve_Erosion(ByVal BeginPeriod As Long, ByVal EndPeriod As Long, ByVal FADescription As String)
On Error GoTo Err_Retrieve
strSQL = "SELECT dbo.DISTRICTS.strDistrict FROM dbo.DISTRICTS;"
Debug.Print "SQL Statement reads " & strSQL
'Clear Prior Data
Sheets("DATA").Select
Range("F8").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.ClearContents
Range("F8").Select
Debug.Print "Retrieve Begin " & BeginPeriod
Debug.Print "Retrieve End " & EndPeriod
Debug.Print "Retrieve Family " & FADescription
Application.Calculation = xlCalculationManual
'Set destination
Set Destination = [DATA!F8]
'Create RecordSet
Set Rs = New ADODB.Recordset
Rs.Open strSQL, MyConn, adOpenForwardOnly, adLockReadOnly, adCmdText
Rw = Destination.Row
Col = Destination.Column
c = Col
Do Until Rs.EOF
For Each MyField In Rs.Fields
Cells(Rw, c) = MyField
c = c + 1
Next MyField
Rs.MoveNext
Rw = Rw + 1
c = Col
Loop
Set Rs = Nothing
Application.CalculateFullRebuild
Application.Calculation = xlCalculationAutomatic
ThisWorkbook.Save
MsgBox "Data Imported and Spreadsheet Saved!", vbExclamation, "MYCOMPANY Financial Planning and Analysis"
Exit_Retrieve:
Exit Sub
Err_Retrieve:
Debug.Print Err.Number & " - " & Err.Description
Resume Exit_Retrieve
End Sub
MS Access 20 years, SQL hack