自定义功能太慢了

时间:2012-11-13 17:04:50

标签: vba ms-access

我创建了一个在查询中使用的自定义函数。该函数打开一个小表(50个单元格),并根据查找结果向查询中的一列添加日期。该函数执行速度太慢,我认为可能是因为我打开并关闭查询中每条记录的记录集。有没有办法避免打开记录集并在每次调用函数时关闭它?我怀疑这首先违背了使用函数的目的,但我希望有人有解决方案。

在原帖后添加。

基于下面的结构,我需要从表中获取查询中的CustomFunctionField,并且日期字段是连接。该表包含日期范围,查询在日期范围内具有特定日期。

- Query-- ID |信息|日期| CustomFunctionField

- Table-- ID | StartDate | EndDate |描述

以下是代码:

Public Function SelectTerm(DateFull)

    Dim rstin As DAO.Recordset
    Dim dx As Date
    Dim dterm As String

    Set rstin = CurrentDb.OpenRecordset("tblTerms", dbOpenSnapshot)

    dx = "1/1/2000"

    If Not rstin.EOF And Not rstin.BOF Then
        Do Until rstin.EOF Or dx >= DateFull
            dx = rstin.Fields("DateEnd")
            rstin.MoveNext
        Loop

        rstin.MovePrevious
        dterm = rstin.Fields("Description")
        rstin.Close
    End If

    SelectTerm = dterm

End Function

1 个答案:

答案 0 :(得分:1)

使用相关子查询根据主表中的日期/时间字段tblTermsDateFull查找术语说明。

SELECT
    y.DateFull,
    (
        SELECT TOP 1 [Description]
        FROM tblTerms
        WHERE DateEnd <= y.DateFull
        ORDER BY DateEnd DESC
    ) AS term_description
FROM YourTable AS y;

相关的子查询并不完全以炽热的性能着称。但是,这种方法应该比打开记录集并在行中移动直到找到所需值的UDF快得多。

相关问题