【问题标题】:How to test if item exists in recordset?如何测试记录集中是否存在项目?
【发布时间】:2013-08-20 02:03:04
【问题描述】:

我有一个正在加载到记录集中的交叉表查询。然后,我将查询字段写入 Excel 电子表格。问题是根据查询结果可能不存在字段。

例如,我有以下行:

oSheet5.Range("F1").Value = rsB2("AK")

...这会将名为“AK”的记录集项目的值写入电子表格。但如果“AK”不存在,我会收到错误Item not found in this collection

如何测试是否有名为“AK”的项目?

我试过了……

If rsB2("AK") Then
    oSheet5.Range("F" & Count).Value = rsB2("AK")
End If

...但那没有用。

我也试过了……

If rsB2("AK") Is Nothing Then
    oSheet5.Range("F" & Count).Value = ""
Else
    oSheet5.Range("F" & Count).Value = rsB2("AK")
End If

...仍然是同样的错误。

有 50 多个项目/字段要检查 .. 美国的所有州以及一些额外内容。 谢谢!

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:

    你可以使用Recordset.FindFirst Method (DAO)看看herehere

    小例子:

    Sub FindOrgName()
    
    Dim dbs As DAO.Database
    Dim rst As DAO.Recordset
    
    'Get the database and Recordset
    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("tblCustomers")
    
    'Search for the first matching record   
    rst.FindFirst "[OrgName] LIKE '*parts*'"
    
    'Check the result
    If rst.NoMatch Then
        MsgBox "Record not found."
        GotTo Cleanup
    Else
        Do While Not rst.NoMatch
            MsgBox "Customer name: " & rst!CustName
            rst.FindNext "[OrgName] LIKE '*parts*'"
        Loop
    
        'Search for the next matching record
        rst.FindNext "[OrgName] LIKE '*parts*'"
    End If
    
    Cleanup:
        rst.Close
        Set rst = Nothing
        Set dbs = Nothing
    
    End Sub
    

    【讨论】:

    • 虽然这可行,但 Recordset.Findfirst 可能会非常缓慢。我认为它忽略了索引。使用 Recordset.Seek 可能会更好。
    【解决方案2】:

    您可以添加一个错误处理程序来捕获未找到项目的错误...忽略它和/或执行其他操作。

    或者如果第一个记录集字段总是映射到第一个工作表列而不管字段的名称,您可以通过其序号位置引用它:rsB2(0)

    或者您可以在尝试检索其值之前检查记录集的Fields 集合以确认字段名称是否存在。

    打开记录集后,加载带有字段名称的字典。此代码示例使用后期绑定。如果您想要提前绑定,我会提供注释提示。早期绑定需要您为 Microsoft Scripting Runtime 设置引用。

    Dim objDict As Object 'Scripting.Dictionary
    'Set objDict = New Scripting.Dictionary
    Set objDict = CreateObject("Scripting.Dictionary")
    Dim fld As DAO.Field
    
    For Each fld In rsB2.Fields
        objDict.Add fld.Name, vbNullString
    Next
    

    然后你可以使用字典的Exists 方法来发挥你的优势。

    If objdict.Exists("AK") = True Then
        oSheet5.Range("F1").Value = rsB2("AK")
    End If
    

    【讨论】:

    • 这就是我想要做的......检查记录集以查看是否存在名为“AK”的字段,然后再访问它的值。这是怎么做的? If rsB2("AK") exists then cell.value = rsB2("AK") 之类的东西。我只是不知道 VBA 语法:)
    • Excel 文件看起来像 F1 = "AK", G1 = "AL", H1 = "AR" .. 所以 F2 必须是 rsB2("AK"),G2 必须是 rsB2("AL") .. 等等。
    • 这就是我要找的……谢谢!
    猜你喜欢
    • 2019-06-04
    • 2014-01-12
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多