|
|
Функция GetData() - Возврат значения из поля таблицы (запроса) по условиям (DAO и ADO)
Часто нужно "вытащить" значение поля конкретной записи определённой таблицы (запроса).
Для этого есть функция DLookup()
Это её аналог, но побыстрее и функциональнее.
Public Function GetData(sExpression As String, sSource As String, _
Optional vCriteria As Variant = Null, _
Optional vDefault As Variant = Null, _
Optional vOptions As Variant = Null) As Variant
Dim str As String
Dim rst As DAO.Recordset
On Error GoTo GetData_Err
str = "SELECT " & sExpression & " FROM " & sSource & (" WHERE " + vCriteria) & (" " + vOptions)
Set rst = CurrentDb.OpenRecordset(str, dbReadOnly)
GetData = rst.Fields(0)
If IsNull(GetData) = True Then GetData = vDefault
GetData_Bye:
On Error Resume Next
rst.Close: Set rst = Nothing
Exit Function
GetData_Err:
GetData = vDefault: Err.Clear: Resume GetData_Bye
End Function
Примеры:
Dim v As Variant
v = GetData("Код_Товара & ("" - "" + Название_Товара)", "Справочник_Товаров", "Товар_ID=33", "Не Найдено!")
v = GetData("Max(DetID)", "dtDet", 0) + 1
Public Function GetData(sExpression$, sSourсe$, Optional vCriteria As Variant = Null, _
Optional vDefault As Variant = Null, _
Optional vOptions As Variant = Null) As Variant
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sSql$
On Error GoTo GetData_Err
Set cnt = CurrentProject.Connection
Set rst = CreateObject("ADODB.Recordset")
sSql = "SELECT " & sExpression & " FROM " & sSourсe & (" WHERE " + vCriteria) & (" " + vOptions)
rst.Open sSql, cnt, adOpenStatic, adLockReadOnly
GetData = rst.Fields(0)
If IsNull(GetData) = True Then GetData = vDefault
GetData_Bye:
On Error Resume Next
rst.Close: Set rst = Nothing
cnt.Close: Set cnt = Nothing
Exit Function
GetData_Err:
GetData = vDefault: Err.Clear: Resume GetData_Bye
End Function
|
|