使用宏循环遍历Excel电子表格

时间:2016-04-05 14:47:50

标签: sql-server vba excel-vba macros excel

我试图遍历excel单元格以从sql server表中获取值。我已经编写了一个宏,它将从excel和查询sql server故事中取出jobnumber以获取客户详细信息并将其转储到电子表格中。到目前为止,我只能获得单个细胞的数据。如何循环遍历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

End Sub

1 个答案:

答案 0 :(得分:1)

您可以使用IN SQL语句执行此操作:

SELECT customer FROM job_tab WHERE jobnum2 IN ( 'Value1', 'Value2', ... );

因此,您必须循环遍历表A列中的所有客户并更改SQL请求以使用上述语句:

Sub ConnectSqlServer()

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim newrow As String


'MODIFIED: create the search string for the IN-Statement
newrow = "("
For i = 1 To Worksheets("Sheet1").Cells(Worksheets("Sheet1").Rows.Count, "A").End(xlUp).Row
    newrow = newrow & "'" & Trim(Worksheets("Sheet1").Cells(i, "A").value) & "',"
Next i
newrow = Left(newrow, Len(newrow) - 1)
newrow = newrow & ")"

' 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
'MODIFIED: altered the SQL statement to use the search string with IN
Set rs = conn.Execute("SELECT customer FROM job_tab where jobnum2 IN " & 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
End Sub
相关问题