Solved

Execute SQL statement from VBA (Excel)

Posted on 2004-09-12
8
337 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:Kristian_Moritsen
Comment Utility
Hi akoster,

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

Thanks,
Kristian
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 10

Expert Comment

by:anv
Comment Utility
0
 
LVL 19

Expert Comment

by:akoster
Comment Utility
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
Comment Utility
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
Comment Utility
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now