VBA-如何从单独的模块中调用SQL数据库连接

时间:2019-05-29 01:07:18

标签: sql sql-server excel vba

我一直在研究这个问题,但是找不到与之相关的解决方案。我在一个单独的模块(模块5)中有一个SQL数据库连接,当我需要从另一个模块/表单连接到数据库时,我想调用它。这是为了简单和一次更新,所以我不需要遍历每个函数来更新连接。

数据库连接(模块5)

Function dbconnection()
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

cnn.Open = "Driver={SQL Server};Server=HOLAP- 
IST9985\CASETRACKER;Database=casetracker; Trusted_Connection=Yes"


cnn.Close
Set cnn = Nothing

End Function

这是我需要调用连接(Module2)的地方-将查询发送到数据库,并将结果显示在我的列表框中。

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset


rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn, 
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If

End Function

2 个答案:

答案 0 :(得分:0)

您可以从函数中返回连接:

Function dbconnection() as ADODB.connection

    Dim cnn As New ADODB.connection

    cnn.Open = "Driver={SQL Server};Server=HOLAP-IST9985\CASETRACKER;" & _
               "Database=casetracker; Trusted_Connection=Yes"

    Set dbconnection = cnn

End Function

然后使用它:

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

Set cnn = dbconnection()
rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn, 
adOpenStatic
If rst.EOF = False Then
'etc etc

答案 1 :(得分:0)

这就是我想出的解决连接问题的方法。

dbconnection:

Public sqlt As String
Function dbconnection() As ADODB.connection
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

sqlt = "Driver={SQL Server};Server=HOLAP- 
IST9985\CASETRACKER;Database=storecons; Trusted_Connection=Yes"
End Function

调用dbconnection:

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

Set cnn = Module5.dbconnection()
cnn.Open sqlt


rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn, 
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If
End Function