I have the (final) code I got on the internet. In this line of code it gives error in WHERE, since it is a text:
strSQL = " SELECT [VENDAS$].[Data], [VENDAS$].[Vendedor], [VENDAS$].[Total]" & _
" FROM [VENDAS$] WHERE [VENDAS$].[Vendedor] = Murilo;"
Substituting for this below does not give error in WHERE, being a number:
strSQL = " SELECT [VENDAS$].[Data], [VENDAS$].[Vendedor], [VENDAS$].[Total]" & _
" FROM [VENDAS$] WHERE [VENDAS$].[Total] >= 100000;"
And I ask: do you need this semicolon at the end?
Follow the complete code, and also ask: Need to set Nothing at the end of the code for the variables conn, rst, and fld? For full code to run, do I need to add some Reference?
Sub RunSQL()
On Error GoTo ErrHandle
Dim conn As Object, rst As Object
Dim strConnection As String, strSQL As String
Dim wkCaminho, wkArquivo As String
Dim I As Integer
Dim fld As Object
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
wkCaminho = ThisWorkbook.Path & "\"
wkArquivo = "MATRIZ DE DADOS.xlsx"
ActiveSheet.Cells.Delete
' Hard code database location and name
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='" & wkCaminho & wkArquivo & "';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
' strSQL = " SELECT [VENDAS$].[Data], [VENDAS$].[Vendedor], [VENDAS$].[Total]" & _
' " FROM [VENDAS$] WHERE [VENDAS$].[Total] >= 100000;"
strSQL = " SELECT [VENDAS$].[Data], [VENDAS$].[Vendedor], [VENDAS$].[Total]" & _
" FROM [VENDAS$] WHERE [VENDAS$].[Vendedor] = Murilo;"
' Open the db connection
conn.Open strConnection
rst.Open strSQL, conn
' column headers
I = 0
Worksheets("Results").Range("A1").Activate
For Each fld In rst.Fields
ActiveCell.Offset(0, I) = fld.Name
I = I + 1
Next fld
' data rows
Worksheets("Results").Range("A2").CopyFromRecordset rst
rst.Close
conn.Close
MsgBox "Successfully ran SQL query!", vbInformation
Exit Sub
ErrHandle:
MsgBox Err.Number & " = " & Err.Description, vbCritical
Exit Sub
End Sub