我正在尝试在Outlook中创建一些自定义按钮,这些按钮与Access数据库中包含的表进行交互。到目前为止,我的按钮在Outlook中工作,运行代码实例化自定义数据访问类,该类又处理打开和关闭与数据库的连接。据我所知,这很有用。
但是,从这个类中,我什至无法执行简单的选择查询。谁能帮助我了解为什么下面的代码可能行不通?我总是以一个没有行的记录集结尾,但是如果我使用Access查询设计器运行相同的sql,它就可以正常工作。
Public Function GetJobID(ByVal xEmailID As String) As Integer
'Returns the JobID associated with a given EmailID from the email link table.
'Returns a fail constant if no link exists.
Dim rs As ADODB.Recordset
Dim sql As String
'Exit if not connected.
'Cast to boolean because VBA doesn't recognise connection state integer as boolean.
If Not CBool(mConn.State) Then
GetJobID = RESULT_FAIL_INTEGER
Exit Function
End If
sql = "SELECT [JobID] FROM [EMAIL_LINK_TABLE] WHERE [EmailID]='xEmailID'"
sql = Replace(sql, "EMAIL_LINK_TABLE", EMAIL_LINK_TABLE)
sql = Replace(sql, "xEmailID", xEmailID)
On Error Resume Next
Set rs = mConn.Execute(sql)
If rs.RecordCount > 0 Then
GetJobID = rs(1).Value
Else
GetJobID = RESULT_FAIL_INTEGER
End If
End Function
答案 0 :(得分:1)
我发现您已将问题归结为.RecordCount
返回-1。
这是来自the docs的动态游标的标准行为:
Recordset对象的光标类型影响是否可以确定记录数。对于仅向前的游标,RecordCount属性将返回-1;静态或键集游标的实际计数;以及动态游标的-1或实际计数,具体取决于数据源。
当然,您可以修改代码以使用静态游标,但这会影响性能。相反,要测试记录集中是否有记录,请使用.EOF
(一种返回布尔值以指示记录集当前是否位于文件末尾的方法)。当只需要加载第一个记录时,这将节省您的代码,而不必加载所有记录:
Public Function GetJobID(ByVal xEmailID As String) As Integer
'Returns the JobID associated with a given EmailID from the email link table.
'Returns a fail constant if no link exists.
Dim rs As ADODB.Recordset
Dim sql As String
'Exit if not connected.
'Cast to boolean because VBA doesn't recognise connection state integer as boolean.
If Not CBool(mConn.State) Then
GetJobID = RESULT_FAIL_INTEGER
Exit Function
End If
sql = "SELECT [JobID] FROM [EMAIL_LINK_TABLE] WHERE [EmailID]='xEmailID'"
sql = Replace(sql, "EMAIL_LINK_TABLE", EMAIL_LINK_TABLE)
sql = Replace(sql, "xEmailID", xEmailID)
On Error Resume Next
Set rs = mConn.Execute(sql)
If Not rs.EOF Then
GetJobID = rs(0).Value
Else
GetJobID = RESULT_FAIL_INTEGER
End If
End Function