使用变量引用集合时出现“对象无效或不再设置”

时间:2019-06-15 18:16:31

标签: vba ms-access access-vba

在回答this question的过程中,我编写了一个简单的函数来测试MS Access表是否包含所提供数组中的所有字段:

Function ValidateFields(strTbl As String, arrReq As Variant) As Boolean
    Dim fld
    Dim fldTmp As Field
    On Error GoTo err
    For Each fld In arrReq
        Set fldTmp = CurrentDb.TableDefs(strTbl).Fields(fld)
    Next fld
    ValidateFields = True
err:
    Exit Function
End Function
?ValidateFields("TempTable", Array("Field1", "Field2", "Field3"))
False

这可以按预期执行,以提高效率,我尝试将Fields Collection分配给For Each循环之外的变量:

Function ValidateFields(strTbl As String, arrReq As Variant) As Boolean
    Dim fld
    Dim fldTmp As Field
    Dim colFld As Fields
    Set colFld = CurrentDb.TableDefs(strTbl).Fields
    On Error GoTo err
    For Each fld In arrReq
        Set fldTmp = colFld(fld)
    Next fld
    ValidateFields = True
err:
    Exit Function
End Function

现在,如果我注释掉On Error语句,则会收到以下错误,并以行Set fldTmp = colFld(fld)高亮显示为原因:

  

运行时错误'3420':

  对象无效或不再设置。

为什么变量colFldFor Each循环中丢失其值?

1 个答案:

答案 0 :(得分:3)

这里的问题是:

CurrentDb创建当前打开的数据库的DAO.Database对象。您的TableDef是其中的一员。

但是,由于您没有存储该对象,因此在将tabledef复制到对象之后,它会立即关闭并释放,并且成员也将被释放。

存储数据库对象,成员也将保留:

Function ValidateFields(strTbl As String, arrReq As Variant) As Boolean
    Dim fld
    Dim fldTmp As Field
    Dim colFld As Fields
    Dim db As DAO.Database
    Set db = CurrentDb
    Set colFld = db.TableDefs(strTbl).Fields
    On Error GoTo err
    For Each fld In arrReq
        Set fldTmp = colFld(fld)
    Next fld
    ValidateFields = True
err:
    Exit Function
End Function