我需要创建一个excel表,它将一系列字符和数字作为输入,对Access数据库进行检查,然后返回一个与数据库同一行的第7列对应的值。我对VBA知之甚少,我设法编译这段代码,从各种来源获取花絮,如StackOverflow,MS Office网站,ExelForum和AllenBrowne.com
但是,当我运行代码时,我收到一个错误,“没有给出一个或多个必需参数的值”,坦率地说,我很难知道错误源自何处,以及它为什么这样做所以。
我的代码如下:
Sub Query()
On Error GoTo errhandler:
Dim con As String
Dim sql As String
Dim inputc
con = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Jet OLEDB:Engine Type=" & Jet4x _
& "; Data Source=" & "C:\Path\file.mdb;"
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
inputc = Range("B1").Value
sql = "SELECT * FROM TABLE1 WHERE 'Custno' = " & input & ";"
Set cn = New ADODB.Connection
cn.Open con
cn.Execute sql
Set rs = new ADODB.Recordset
rs.Open sql, cn, adOpenKeyset, adLockOptimistic
Debug.Print rs.Fields("7")
MsgBox rs.Fields("7")
Exit Sub
errhandler: MsgBox Err.Description
End Sub
我们非常感谢您提供的任何帮助。
-A
将代码更改为此但现在出现没有值匹配的错误:
Sub Query()
On Error GoTo errhandler:
Dim con As String
Dim sql As String
Dim inputc
con = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Jet OLEDB:Engine Type=" & Jet4x _
& "; Data Source=" & "C:\Path\file.mdb;"
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
inputc = Range("B1").Value
sql = "SELECT * FROM TABLE1 WHERE 'Custno' = 'inputc';"
Set cn = New ADODB.Connection
cn.Open con
cn.Execute sql
Set rs = new ADODB.Recordset
rs.Open sql, cn, adOpenKeyset, adLockOptimistic
Debug.Print rs.Fields("7")
MsgBox rs.Fields("7")
Exit Sub
errhandler: MsgBox Err.Description
End Sub
我检查了数值并正在搜索数据库中存在的值。
答案 0 :(得分:0)
答案 1 :(得分:0)
试试这个:
公共变量:
Public db As DAO.Database
Public rsttemp As DAO.Recordset
Public acApp As Access.Application
检查数据库是否存在并打开它:
Sub CheckDB()
'database path
s = "C:\Path\file.mdb"
If db Is Nothing Then
Set acApp = New Access.Application
acApp.OpenCurrentDatabase s
Set db = acApp.CurrentDb
End If
End Sub
关闭DB
Sub CloseDB()
If Not acApp Is Nothing Then
acApp.CloseCurrentDatabase
End If
End Sub
打开记录集的主要子
Sub SqlExecute()
Call CheckDB
inputc = Range("B1").Value
sql = "SELECT * FROM TABLE1 WHERE Custno = """ & inputc & """;"
Set rsttemp = db.OpenRecordset(sql, dbOpenSnapshot)
MsgBox "Records count: " & rsttemp.RecordCount
MsgBox rsttemp.Fields("7")
rsttemp.Close
Set rsttemp = Nothing
Call CloseDB
End Function
答案 2 :(得分:0)
一些事情:
删除cn.Execute行
使用Print和MsgBox语句(引号)中的字段名称
将Jet4X放在引号内,因为它不是变量
还要确保关闭连接和记录集,并在结尾处设置为Nothing。