Link to home
Start Free TrialLog in
Avatar of Kristian_Moritsen
Kristian_Moritsen

asked on

Execute SQL statement from VBA (Excel)

Hi!

I'm "playing" a little with some reports made in Excel and I want to execute an SQL statement directly from the VBA code. I'm not an expert in SQL or VBA so a little explanation and even better an example with "my own SQL statement" would be really appreciated. I have tried the "easy way" by recording a macro and then executing the SQL statement (from the database query) which works fine BUT since the macro recorder only records 256 characters per string the macro is useless to me (Hmmpf!)

See my SQL statement below....

Thank you in advance,
Kristian

p.s.
I can connect to the SQL database from VBA and everything - it's only the execution of the query which gives me problems.


****************SQL STATEMENT*********************
SELECT      I.SalesNumber OrderNo,
      I.InvoiceAccount Account,
      D.Name CustomerName,
      I.Purpose,
      I.OrderTaker,
      I.SalesRep,
      O.AIHandler,
      P.CorporationForm CustomerType,
      P.Classification MarketingGroup,
      CASE O.Ordertype when 0 then 'Sparepart'
                     when 1 then 'Stock delivery'
                   when 2 then 'Accellerated delivery'
                   when 3 then 'Long delivery'
                   else        'Motorcycles' END OrderType,
      CASE O.SalesPhase when 0 then 'Quotation'
                      when 1 then 'Disposal'
                    when 2 then 'Confirmed'
                    when 3 then 'Back order'
                    when 4 then 'Delivered'
                    when 5 then 'Invoiced'
                    else        'Dead' END SalesPhase,
      Sum(I.SalesBalance * (I.ExchangeRate/100)) Sales,
      Sum(I.CostValue) Cost,
      Sum((I.SalesBalance * (I.ExchangeRate/100)) - I.CostValue) GP
FROM      DebInvJour I,
      DebInvTrans L,
      Debtable D,
      SalesTable O,
      SMAProsTable P
WHERE      I.dataset = 'KK'
AND      L.Dataset = 'KK'
AND      D.dataset = 'KK'
AND      O.Dataset = 'KK'
AND      P.Dataset = 'KK'
AND      I.InvoiceDate >= CONVERT(SmallDateTime, '01.12.2003', 104)
AND      I.invoicedate <= CONVERT(SmallDateTime, '31.12.2003', 104)
AND      D.AccountNumber = I.InvoiceAccount
AND      I.InvoiceNumber = L.InvoiceNumber
AND      I.InvoiceDate   = L.InvoiceDate
AND      O.SalesNumber   = I.SalesNumber
AND      P.DebtorAccount = D.AccountNumber
GROUP BY
      I.SalesNumber,
      I.InvoiceAccount,
      D.Name,
      I.Purpose,
      I.OrderTaker,
      I.SalesRep,
      O.AIHandler,
      P.CorporationForm,
      P.Classification,
      O.Ordertype,
      O.SalesPhase
ORDER BY I.SalesNumber
****************SQL STATEMENT END*****************
Avatar of anv
anv

hi  Kristian_Moritsen

could u please explain what exactly u r trying to achive with the query..

so i can give u an SQL that is easy to understand..
Avatar of Kristian_Moritsen

ASKER

Hi anv,

I trying to reurn data from an SQL database to my Excel spreadsheet about some orders in the database. It will give me a header row and a row per order with various informations about the order. I only read from the database.

Hope this is ansver enough.

Kristian
in general a sql data selection query is build using the setup :


SELECT <which data to select> FROM <which table holds the data> WHERE <criteria to match> GROUP BY <sort the data>

from the stuff above :

SELECT I.InvoiceAccount, D.Name FROM I, D WHERE D.AccountNumber = I.InvoiceAccount GROUP BY I.InvoiceAccount

selects names from table D relating to the account numbers from table I.
Hi akoster,

Yeah, but I can't make this work in VBA - could you copy/past an exampel of that?

Thanks,
Kristian
use this code as an example to get the customers with names and adresses out of the northwind database (supplied with ms office for demonstration purposes)


    With ActiveSheet.QueryTables.Add(Connection:=Array(Array( _
        "ODBC;DBQ=C:\Nwind.mdb;DefaultDir=C:\;Driver={Microsoft Access Driver (*.mdb)};DriverId=281;FIL=MS Access;MaxBufferSize=2048;MaxScanR" _
        ), Array( _
        "ows=8;PageTimeout=5;SafeTransactions=0;Threads=3;UID=admin;UserCommitSync=Yes;" _
        )), Destination:=Range("A1"))
        .Sql = "SELECT DISTINCT Customers.CustomerID, Customers.ContactName, Invoices.CustomerID, Invoices.Address FROM Customers, Invoices WHERE Customers.CustomerID = Invoices.CustomerID ORDER BY Customers.ContactName"
        .FieldNames = True
        .RefreshStyle = xlInsertDeleteCells
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .RefreshOnFileOpen = False
        .HasAutoFormat = True
        .BackgroundQuery = True
        .TablesOnlyFromHTML = True
        .Refresh BackgroundQuery:=False
        .SavePassword = True
        .SaveData = True
    End With

if the northwind database is not present at you system you can download it :
http://www.microsoft.com/downloads/details.aspx?FamilyID=C6661372-8DBE-422B-8676-C632D66C529C&displaylang=EN


for more info on sql statements :
http://www.w3schools.com/sql/default.asp
Kristian_Moritsen,

How are you currently retrieving data into Excel?  Are you using ADO?  What is your database (SQL Server, Access, Oracle, etc?

Leon
ASKER CERTIFIED SOLUTION
Avatar of Sasho
Sasho

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial