简体   繁体   中英

Excel VBA - Get Data from SQL based of Cell range values

I've been tasked to get data from a SQL DB based off the values in Column A Row 3 onwards.

Example of Excel Sheet:

ITEM   | QTY TO PICK | QTY ON ORDER | Column 2 | Column 3 etc

PART 1 |      5      | <Data will be populated here>

PART 2 |      12     | <Data will be populated here>

This code runs through a Command Button.

The data pulled from SQL will be populated starting in C3 onwards.

However, my below code only returns one row at a time.

I know where I need to make changes, I just don't know what. After at least 2 hours googling, I'm thoroughly stumped.

ItemNumber = Range("A3").Value

I've tried amending to ("A3:A100").Value but I just get errors.

Full code below;

Private Sub CommandButton2_Click()

' Create a connection object.
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection

' Provide the connection string.
Dim strConn As String

'Use the SQL Server OLE DB Provider.
strConn = "Provider=SQLOLEDB;"

'Connect to the Pubs database on the local server.
strConn = strConn & "server=<server name>;INITIAL CATALOG=<DB Name>;"

'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"

'Now open the connection.
cn.Open strConn

'
'

ActiveSheet.Range("C3:G10000").Clear ' clear out existing data
Dim ItemNumber As String

ItemNumber = Range("A3").Value

' Create a recordset object.
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

SQLStr = "Select * from vw_WorksOrder WHERE ITEMNO = " & ItemNumber & ""

rs.Open SQLStr, cn

' Copy the records into cell A1 on Sheet1.
Sheet4.Range("C3").CopyFromRecordset rs

' Tidy up

rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing

My advise is:

1.)

Create a table on SQL Server which contains parameters for your sql statement (itemnumber = 1)

2.) Write a cycle which loops tru the ranges and adds values one by one to the table like:

i = 1 while cells(i,3).value <> "" ... Insert into temptable values (parameter1,parameter2, etc)

i = i+1 wend

3.)

Modify your sql statement for the recordset joining the table with the parameters and the data you would like to pull and paste that data.

You could try building the SQL like so

"Select * from vw_WorksOrder WHERE ITEMNO in (" & _
join(application.transpose(range("a1:a5").Value),",") & ")"

or, for strings.

  "Select * from vw_WorksOrder WHERE ITEMNO in ('" & _
join(application.transpose(range("a1:a5").Value),"','") & "')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM