Solved

Excel VBA Query

Posted on 2014-02-12
2
388 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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

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

When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
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…

726 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