Solved

Execute SQL statement from VBA (Excel)

Posted on 2004-09-12
8
350 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
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…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

830 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