如何使用带有数据库查询连接的excel vba循环?

时间:2018-01-08 15:55:31

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

我试图在可变范围的细胞上执行循环。 然后使用与单元格文本相关的变量运行查询。 它似乎是循环遍历单元格,但错误在于sql,因为该对象已经打开。我试图先关闭所有连接,但在移动到下一个单元格时会得到相同的错误。

Dim cell as range
dim rng as range
set rng = range("D9:D" & ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
For each cell in rng.Cells
cell.activate

Dim CELL2 as Variant
CELL2 = Activecell

dim cnn as new adodb.connection
dim rst as new adodb.recordset
dim ConnectionString as string
dim StrQuery1 as string
dim PathID as variant

ConnectionString = ' I have inserted relevant data here'


dim xConnect as object
for each xConnect in ActiveWorkbook.Connections
xConnect.delete
Next xConnect

cnn.Open ConnectionString
cnn.CommanTimeout = 900

StrQuery1 = "Declare @DocID int Select @DocId = DocumentID from Documents where Left(Filename,10) = '" & CELL2 "'Right(Filename,6) = 'SLDDRW' Declare @PrjId int Select @PrjId = ProjectID from DocumentsinProjects where DocumentId = @DocId Select Path from Projects where ProjectID = @PrjId

rst.open StrQuery1, cnn

PathID = rst!Path

Msgbox (CELL2)
Msgbox (PathId)

dim xConnect as object
for each xConnect in ActiveWorkbook.Connections
xConnect.delete
Next xConnect

Next Cell

1 个答案:

答案 0 :(得分:0)

我建议使用Close方法进行连接。您可能还想查看在开始时打开连接一次,发送多个sql命令,并在最后关闭它。下面列出了一个简单的例子

Dim cnn As New ADODB.Connection
Dim rst As New ADODB.RecordSet
Dim ConnectionString As String

cnn.Open ConnectionString

For .....
    Set rst = cnn.Execute( Insert SQL String here )
      do things
Next .....

rst.Close
cnn.Close

编辑:在丹的评论之后,这是另一种每次打开和关闭整个连接的方式

Dim cnn As New ADODB.Connection
Dim rst As New ADODB.RecordSet
Dim ConnectionString As String

For .....
    cnn.Open ConnectionString
    Set rst = cnn.Execute( Insert SQL String here )
      do things
    rst.Close
    cnn.Close
Next .....