我有一个带有组合框的表单,我用来自访问数据库(与数据库分开的用户界面)的记录填充。我想要做的是在程序的整个生命周期中将记录存储在类的实例中,而不是每次用户选择组合框时查询表。代码在调用Sub中失败,可能是由于类中的编码不正确。
这就是我连接数据库的方式:
Option Explicit
Dim DBCONT As Object
Public Function connectDatabase()
Set DBCONT = CreateObject("ADODB.Connection")
Dim strDBPath As String
strDBPath = "C:\Users\rob\Documents\Cyber Security\Database\BackEnd.accdb"
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
DBCONT.Open sConn
'Call closeDatabase
End Function
Public Function closeDatabase()
On Error Resume Next
DBCONT.Close
Set DBCONT = Nothing
On Error GoTo 0
End Function
这是我在将记录作为一个类的实例存储时的尝试。当指定“设置getdevices = Rs”任何想法为什么时,我会收到错误消息类型的错误?:
Option Explicit
Public Rs() As ADODB.Recordset
Function getdevices() As ADODB.Recordset
connectDatabase
Dim Rs As Object
Dim CurDatabase As Object
Set CurDatabase = CurrentDb
Set RS = CurDatabase.OpenRecordset ("SELECT * FROM tblCDA")
Set getdevices = Rs
closeDatabase
Set Rs = Nothing
End Function
SUB CASSS THE CLASS:
Private Sub cboSysDesignation_Click()
Dim rsDevice As Object
Set rsDevice = getdevices(Rs) 'FAILS AT THIS POINT!!! "Object variable or With block variable not set"
DeviceName = cboSysDesignation.Value
rsDevice.MoveFirst
Do Until DeviceName = rsDevice.Fields("DeviceID")
rsDevice.MoveNext
Loop
txtSystemDescription.SetFocus
If rsDevice!DESC <> "" Then
txtSystemDescription.Value = rsDevice!DESC
Else
txtSystemDescription.Value = ""
End If
txtSystemEngineer.SetFocus
If rsDevice!ENGINEER <> "" Then
txtSystemEngineer.Value = rsDevice!ENGINEER
Else
txtSystemEngineer.Value = ""
End If
Set rsDevice = Nothing
End Sub
答案 0 :(得分:2)
你写道:“我在分配时收到错误的消息类型错误”设置getdevices = Rs“任何想法为什么?”
让我们逐步完成你的代码......
Function getdevices() As ADODB.Recordset
connectDatabase
Dim Rs As Object
Dim CurDatabase As Object
Set CurDatabase = CurrentDb
CurrentDb
是DAO.Database
个对象。
Set RS = CurDatabase.OpenRecordset ("SELECT * FROM tblCDA")
DAO.Database.OpenRecordset
方法返回 DAO 记录集。
Set getdevices = Rs
getdevices
已宣布为As ADODB.Recordset
,但Rs
为DAO.Recordset
。他们的类型不匹配。