Solved

Execute SQL statement from VBA (Excel)

Posted on 2004-09-12
8
355 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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:Arno Koster
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

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:Arno Koster
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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
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…

739 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