我正在Excel VBA中编写一个函数,它将被调用以从Access数据库中提取数据,我正在使用ADO连接。函数Get_g_gtop具有定义为波纹管的参数。现在,我尝试使用命令对象从记录集中获取值,但是,我收到错误消息3021:BOF或EOF是真,或者当前记录已被删除。请求的操作需要当前记录。调试指向该行:Get_g_gtop = rst.Fields(0).Value。
在Access中查询的SQL语句有什么问题吗?任何建议都会非常感激!
冰
函数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
结束功能
答案 0 :(得分:0)
打开记录集(Set rst = cmd.Execute
)后,在尝试访问该数据之前,必须检查它是否包含任何数据,例如:
if not rst.EOF then
'do your stuff with the data
end if
您收到的错误表明您没有从SELECT语句中获取任何记录。 按照HansUp的建议进行检查。