简体   繁体   English

如何在带有数据库查询连接的Excel VBA循环中使用?

[英]How to use an excel vba loop with a database query connection within?

I I'm trying to perform a loop over a variable range of cells. 我正在尝试在可变范围的单元格上执行循环。 A query is then run with varibles relating to the cell text. 然后使用与单元格文本有关的变量运行查询。 It appears to be looping through the cells but the error lies within sql because the object is already open. 它似乎在单元格中循环,但错误在于sql内,因为该对象已打开。 I have tried to close all connections before hand but get the same error as it moves to the next cell. 我曾尝试先关闭所有连接,但在移至下一个单元格时遇到相同的错误。

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

I would suggest using the Close method for the connection. 我建议对连接使用Close方法。 You might also want to look into opening the connection once at the beginning, sending multiple sql commands, and closing it at the end. 您可能还希望在开始时一次打开连接,发送多个sql命令,然后在结束时关闭它。 A quick examples is included below 下面是一个快速示例

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

Edit: After Dan's comment, here is another way that will open and close the entire connection every time 编辑:Dan发表评论后,这是另一种每次打开和关闭整个连接的方法

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 .....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM