【发布时间】:2016-04-05 14:47:50
【问题描述】:
我正在尝试遍历 excel 单元格以从 sql server 表中获取值。我编写了一个宏,它将从 excel 中获取 jobnumber 并查询 sql server 故事以获取客户详细信息并将其转储到电子表格中。到目前为止,我只能获取单个单元格的数据。如何循环遍历 Excel 单元格以获得多个工作编号。我是 VBA 的新手。谢谢你的帮助。这是我的宏:
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim newrow As String
newrow = Worksheets("Sheet1").Cells(1, "A").Value
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=0.0.0.0;" & _
"Initial Catalog=asset;" & _
"User ID=Temp;Password=test123;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute("SELECT customer FROM job_tab where jobnum2='" & Trim(newrow) & "';")
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(1).Range("B1").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
结束子
【问题讨论】:
标签: sql-server vba excel macros