?
Solved

Excel VBA Query

Posted on 2014-02-12
2
Medium Priority
?
400 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
1 Comment
 
LVL 46

Accepted Solution

by:
aikimark earned 2000 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

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

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

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.
This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

850 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