VBA Access getting RowSource to find lookup values

前端 未结 2 1582
一向
一向 2021-01-16 12:40

VBA noob here (as of this mourning),

In MS Access I wrote a test function to find the value of a record base on some criteria you pass in.

The function seems

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 13:12

    If I understand your question correctly, I think using a parameter query will solve your problem. Using parameters is good practice since they will perform implicit data type casts and also prevent injection attacks.

    Notice in the following function, I changed the lookupValue to a Variant type, which allows you to pass any type of value to the function.

    Public Function lookUpColumnValue( _
        database As DAO.database, _
        column As String, _
        table As String, _
        lookUpColumn As String, _
        lookUpValue As Variant) As String
    
        Dim sql As String
        Dim recordSet As DAO.recordSet
        Dim result As String
        Dim qd As QueryDef
        Set qd = database.CreateQueryDef("")
        sql = "SELECT [" + table + "].[" + column + "] FROM [" + table + "] " & _
              "WHERE [" + table + "].[" + lookUpColumn + "] = [parm1];"
        qd.sql = sql
        qd.Parameters![parm1] = lookUpValue
        Set recordSet = qd.OpenRecordset()
    
        result = recordSet(column)
    

    EDIT

        lookUpColumnValue = DLookup("Space Use Description", "Space Use Codes", result)
    
    
    End Function
    

提交回复
热议问题