我正在尝试使用 vba 从 Excel 运行 SQL 语句。我需要做的就是运行 select 语句并使用数组 Array1 和 Array2 中的值。Array1 和 Array2 存储两列的 WHERE 条件。
例如
for i=0 to UBOUND(Array1) 'UBOUND for Array2 will always be equal to UBOUND for Array1
sql = "SELECT name, address, state, zip WHERE
fname='" & Array1(i) & "' AND lname= '" & Array2(i) &"'"
open rs.sql
sheets(1).range("A1").CopyFromRecordset rs
Next
似乎它似乎不起作用。我想我没有正确使用循环。有人可以建议我在这里做错了什么吗?
非常感谢您调查它。
编辑1:
连接参数:
下面是代码:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
'database credentials
Dim uName As String, uPass As String
Dim strConnect As String
strConnect = "Driver={SQL Server Native Client 10.0};" & "Server=[servername]" & "Database=[dbname] ;Uid=" & uname & ";Pwd=" & upass & ";trusted connection=yes"
cn.ConnectionString = strConnect
cn.Open
for i=0 to UBOUND(Array1) 'UBOUND for Array2 will always be equal to UBOUND for Array1
sql = "SELECT name, address, state, zip FROM XYZ WHERE
fname='" & Array1(i) & "' AND lname= '" & Array2(i) &"'"
With rs
.ActiveConnection = cn
.Open sql
...[code to check for EOF/BOF, if not EOF or BOF then paste in pre defined cells]
sheets(1).range("A1").CopyFromRecordset rs
Next
end with
rs.close
cn.close