Solved

Excel VBA Query

Posted on 2014-02-12
2
387 Views
Last Modified: 2014-02-13
Is it possible to better rewrite the query in Excel VBA using parameter query or other better way to handle multiple parameters, Tks

'Retrieve record from SQL Server
Set cnt = New ADODB.Connection
    

stADO = "Provider=SQLOLEDB.1;" & _
        "Data Source=xxxx;Initial Catalog=Dynamics_BAK;User ID=report;Password=123"

    
With cnt
    .CursorLocation = adUseClient
    .Open stADO
    .CommandTimeout = 0
End With


'SQL Statement
stSQL = "select  * from WMSORDERTRANS where SHIPMENTID = 'A10009480'  order by linenum"

Set rst = cnt.Execute(stSQL)
    

If rst.RecordCount <> 0 Then
    rst.MoveFirst
    Do
        MsgBox rst("itemid")
        rst.MoveNext
    Loop Until rst.EOF
    rst.Close
End If

Open in new window

0
Comment
Question by:AXISHK
2 Comments
 
LVL 45

Accepted Solution

by:
aikimark earned 500 total points
ID: 39856381
You can construct a list of values and use the IN () clause.  I assume that you would pull these values from your worksheet.
Dim strShipIDs As String
strShipIDs = "'A10009480'"
strShipIDs = strShipIDs & ", " & "'A10009481'"
strShipIDs = strShipIDs & ", " & "'A10009482'"
strShipIDs = "(" & strShipIDs & ")"

'SQL Statement
stSQL = "select  * from WMSORDERTRANS where SHIPMENTID In " & strShipIDs & "  order by linenum"

Open in new window


Also, you can use a range of values with the Between clause:
'SQL Statement
stSQL = "select  * from WMSORDERTRANS where SHIPMENTID Between 'A10009480' And 'A10009482' order by linenum"

Open in new window

0

Featured Post

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.

Question has a verified solution.

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

This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Some code to ensure data integrity when using macros within Excel. Also included code that helps secure your data within an Excel workbook.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

839 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