1

所以我有一个 MS Access 数据库,我需要编写一个 VBA 代码来查找并显示某个值。

这是我到目前为止所拥有的,但它没有做任何事情

Public Function findInDb()
Dim mySQL As String
Dim custID As Integer

custID = "13"

mySQL = "SELECT Orders.CustomerID FROM Orders  " & _
       "WHERE [CustomerID] = orderDate"

DoCmd.RunSQL mySQL


End Function

知道我做错了什么吗?

4

3 回答 3

0

DoCmd.RunSQL 不返回任何结果。因此,它运行查询,但结果 CustomerID 值无法返回给您。

Santosh 建议使用 DLookup,但从性能角度来看,这非常糟糕。我建议使用 ado;为此,您需要添加对“Microsoft ActiveX 数据对象”的最新(最高编号)库的引用,该库出现在您的 ms 访问副本的引用列表中。使用此参考定义使用此代码:

dim intCustID as long
dim rst as object
set rst = createObject("ADODB.Recordset")
rst.open "SELECT CustomerID FROM Orders WHERE CustomerID = " & CustID _
    , currentproject.connection, adOpenStatic, adLockReadOnly
intCustID = rst.fields(0)  'or if you prefer rst!CustomerID
set rst = nothing
于 2013-10-31T03:18:26.733 回答
0

你可以DlookUp改用。

Public Function findInDb()

    Dim intCustID As Integer, custID As Integer
    custID = 13

    intCustID = DLookup("[CustomerID]", "Orders", "[CustomerID]=" & custID)

End Function

Docmd.RunSQL仅适用于操作查询(追加、更新、删除)。它不适用于 Select 语句。

于 2013-10-31T02:57:59.347 回答
0

内置函数比外部库更受欢迎。

另一种方式

Sub test()

    Dim rsCust As DAO.Recordset
    Dim db As Database
    Set db = CurrentDb

    Dim custID As Integer, resultCust As Integer
    custID = 2

    Dim mySQL As String
    mySQL = "SELECT CustomerID FROM [Orders] WHERE CustomerID =" & custID

    Set rsCust = db.OpenRecordset(mySQL)
    resultCust = IIf(rsCust.EOF And rsCust.BOF, -1, rsCust(0))

End Sub
于 2013-10-31T03:46:04.153 回答