2011-10-05 32 views
0

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

在Access中查询SQL语句有什么问题吗?任何意见将不胜感激!

功能Get_g_gtop(BYVAL VehType作为字符串,BYVAL速度为单)作为变

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 

端功能

+0

如果您将代码示例降低到仅重现问题所需的最小值,并将这些长行分开,以便我们不需要滚动浏览器窗口来阅读它,则这对我们来说更容易排除故障。 – HansUp

+1

@HansUp:...或者它们*扩展*代码示例以包含SQL DDL和SQL DML以重新创建表和示例数据以重现该问题;) – onedaywhen

回答

0

后您打开记录(Set rst = cmd.Execute),你必须检查是否包含任何数据,例如:

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

Reference on w3schools.com

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

相关问题