Excel and SQL - Connection between Excel file

1

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
    
asked by anonymous 07.07.2018 / 22:12

1 answer

0

You need to put single quotes when it comes to characters, with numbers you do not need as you have tested yourself. Try to put it like this: "FROM [SALES $] WHERE [SALES $]. [Vendor] = 'Murilo' ; '     

10.07.2018 / 14:48