0

我正在尝试使用 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
4

1 回答 1

0

终于明白了。几件事 - 1. 由于公式错误,数组 1 为空。一旦我解决了这个问题,我就可以让查询运行。其次,遵循循环中的构造:

cn.open
 for i=lbound(array1) to rbound(array2)
    sql="SELECT name, address, state, zip FROM XYZ WHERE fname='" & Array1(i) & "' AND lname= '" & Array2(i) &"'""
    rs.open sql, cn
    sheets(1).range("A2").copyfromrecordset rs
    rs.close
 next i
cn.close
于 2013-08-14T03:47:49.340 回答