Solved

Execute SQL statement from VBA (Excel)

Posted on 2004-09-12
8
344 Views
Last Modified: 2013-12-25
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*****************
0
Comment
Question by:Kristian_Moritsen
  • 2
  • 2
  • 2
  • +2
8 Comments
 
LVL 10

Expert Comment

by:anv
ID: 12041577
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..
0
 

Author Comment

by:Kristian_Moritsen
ID: 12041666
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
0
 
LVL 19

Expert Comment

by:akoster
ID: 12041760
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.
0
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 

Author Comment

by:Kristian_Moritsen
ID: 12041771
Hi akoster,

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

Thanks,
Kristian
0
 
LVL 10

Expert Comment

by:anv
ID: 12042055
0
 
LVL 19

Expert Comment

by:akoster
ID: 12043140
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
0
 
LVL 29

Expert Comment

by:leonstryker
ID: 12043770
Kristian_Moritsen,

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

Leon
0
 
LVL 3

Accepted Solution

by:
Sasho earned 250 total points
ID: 12050264
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question