我最近为作业编写了一些内容,但由于没有关闭连接而丢失了标记,我对两件事感到好奇。首先,VBA的ADODB连接会在几秒后自然超时,我是否会覆盖下面包含的代码的连接,或者我最终会有多个ADODB连接?从本质上讲,如果不关闭连接,我做错了吗?谢谢。
Option Explicit
'Declaring all necessary variables - Global saves me from redeclaring and allows to be carried
Public dbMyDatabase As String, CnctSource As String, Src As String
Public rstNewQuery As ADODB.Recordset, cntStudConnection As ADODB.Connection
Public Selected1st As String
Private Sub Cancel_Click()
Unload Me
Worksheets("Question3").Range("D4:E9").Clear
End Sub
Private Sub Clear_Click()
Worksheets("Question3Products").Range("C3:H42").Clear
End Sub
Private Sub UserForm_Initialize()
'Get database and links it
dbMyDatabase = ThisWorkbook.Path & "\SalesOrders.mdb"
Set cntStudConnection = New ADODB.Connection
CnctSource = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & dbMyDatabase & ";"
cntStudConnection.Open ConnectionString:=CnctSource
'Commence Query for Categories
Set rstNewQuery = New ADODB.Recordset
rstNewQuery.Open Source:="Categories", ActiveConnection:=cntStudConnection
Range("D4").CopyFromRecordset rstNewQuery
Range("D4:E9").Name = "BufferRange"
TheList.RowSource = "BufferRange"
TheList.Selected(1) = True
'Input Into Listbox
'Decided that clearing the values for connections would be redundant and wasteful.
End Sub
Private Sub FindInfo_Click()
Dim i As Integer
'Switching Sheets and Clearing Previous Variables
Worksheets("Question3Products").Activate
Range("C3:H42").Clear
'Selecting Value user wishes to search for
For i = 0 To TheList.ListCount - 1
If TheList.Selected(i) Then
Selected1st = TheList.List(i)
End If
Next i
'Commence query to search. Decided not to make a function to call upon due to different variables and only 2 instances of use
dbMyDatabase = ThisWorkbook.Path & "\SalesOrders.mdb"
Set cntStudConnection = New ADODB.Connection
CnctSource = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & dbMyDatabase & ";"
cntStudConnection.Open ConnectionString:=CnctSource
Set rstNewQuery = New ADODB.Recordset
Dim StringUse As String
StringUse = "SELECT* From Products WHERE CategoryID = " & Selected1st
rstNewQuery.Open Source:=StringUse, ActiveConnection:=cntStudConnection
Range("C3").CopyFromRecordset rstNewQuery
Range("F3:F42").Style = "Currency"
End Sub