【问题标题】:Error 3021, no current record has been found, Query data from Access to Excel错误 3021,没有找到当前记录,从 Access 查询数据到 Excel
【发布时间】:2011-12-01 14:59:38
【问题描述】:

我正在 Excel VBA 中编写一个函数,该函数将被调用以从 Access 数据库中提取数据,我正在使用 ADO 连接。 Get_g_gtop 函数的参数定义如下。现在,我尝试使用命令对象从记录集中获取值,但是,我收到错误消息 3021:BOF 或 EOF 为真,或者当前记录已被删除。请求的操作需要当前记录。调试指向以下行:Get_g_gtop = rst.Fields(0).Value。

Access中查询的SQL语句有问题吗?任何建议将不胜感激!

必应

Function Get_g_gtop(ByVal VehType As String, ByVal Speed As Single) As Variant

Dim Dbfilepath As String

Dbfilepath = "C:\Users\sevenice\Desktop\EM Database.accdb"

Set cnn = New ADODB.Connection

cnn.Open "Provider= Microsoft.ACE.OLEDB.12.0;" & " Data Source=" & Dbfilepath & ";" & "Persist Security Info =False;"

'Set rst = New ADODB.Recordset

Set cmd = New ADODB.Command
cmd.ActiveConnection = cnn

'Dim QueryStr As String
Dim S As Single

If StrComp(VehType, "LDV") * StrComp(VehType, "LDT") * StrComp(VehType, "LHD<=14K") * StrComp(VehType, "LHD<=19.5K") = 0 Then
   S = 35.6
   'QueryStr = "SELECT [g/gtop] FROM [EM Database].[N (t) Data] WHERE [Vehicle Category]= "" & VehType & "" AND S = 35.6 " & " AND [Speed Lower] <= " & Speed & " AND [Speed Upper] >= " & Speed & ";"

   cmd.CommandText = "SELECT [g/gtop] FROM [EM Database].[N (t) Data] WHERE [Vehicle Category]= "" &  VehType & "" AND S = 35.6 " & " AND [Speed Lower] <= " & Speed & " AND [Speed Upper] >= " & Speed & ";"
   'rst.Open QueryStr, cnn

   Set rst = cmd.Execute

   Get_g_gtop = rst.Fields(0).Value

ElseIf StrComp(VehType, "MHD") * StrComp(VehType, "HHD") * StrComp(VehType, "Urban Bus") = 0 Then
   S = 26.7
   QueryStr = "SELECT [g/gtop] FROM [EM Database].[N (t) Data] WHERE [Vehicle Category]=" & VehType & " AND S = 26.7 " & " AND [Speed Lower] <= " & Speed & " AND [Speed Upper] >=" & Speed & ";"
   rst.Open QueryStr, cnn
   Get_g_gtop = rst.Fields(0).Value

End If

结束函数

【问题讨论】:

  • 如果您将代码示例剥离到重现问题所需的最低限度,并拆分这些长行以便我们无需滚动浏览器窗口来阅读它们,这将更容易让我们排除故障.
  • @HansUp: ...或者如果他们扩展代码示例以包含 SQL DDL 和 SQL DML 以重新创建表和示例数据以重现问题;)跨度>

标签: excel ms-access vba


【解决方案1】:

打开记录集 (Set rst = cmd.Execute) 后,您必须检查它是否包含任何数据,然后再尝试访问该数据,例如:

if not rst.EOF then
'do your stuff with the data
end if

Reference on w3schools.com

您收到的错误表明您没有从 SELECT 语句中获得任何记录。 按照 HansUp 的建议进行检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多