[英]Excel VBA - Get Data from SQL based of Cell range values
我的任務是根據第A列第3行之后的值從SQL DB獲取數據。
Excel工作表示例:
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>
此代碼通過命令按鈕運行。
從C3開始,將填充從SQL提取的數據。
但是,我的以下代碼一次僅返回一行。
我知道我需要在哪里進行更改,我只是不知道要做什么。 經過至少2個小時的谷歌搜索,我徹底迷住了。
ItemNumber = Range("A3").Value
我嘗試過修改為("A3:A100").Value
但是我只是報錯。
完整代碼如下;
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
我的建議是:
1.)
在SQL Server上創建一個表,其中包含sql語句的參數(itemnumber = 1)
2.)編寫一個循環,循環查找范圍並將值一一添加到表中,如下所示:
i = 1,而cells(i,3).value <>“” ...插入到臨時表值中(參數1,參數2等)
我=我+1溫德
3.)
修改您的sql語句,以便將表和參數合並在一起,並在其中添加要粘貼和粘貼的數據的記錄集。
您可以嘗試像這樣構建SQL
"Select * from vw_WorksOrder WHERE ITEMNO in (" & _
join(application.transpose(range("a1:a5").Value),",") & ")"
或者,對於字符串。
"Select * from vw_WorksOrder WHERE ITEMNO in ('" & _
join(application.transpose(range("a1:a5").Value),"','") & "')"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.