我可以在不同的表上使用相同的记录集变量吗?
我是 Microsoft Access 的新手。
如何在不同的表上使用相同的记录集变量?
I am new to Microsoft Access.
How can I use the same recordset variable on different tables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,只要您不希望变量指向两个记录集,就可以。
但问题是你为什么要这么做?您希望节省什么?资源?没什么大不了的。代码的可读性也会受到影响。如果您一周后或其他人稍后查看您的代码,他们可能不会意识到发生了什么。因此我建议每个表/查询一个记录集变量。
还有变量的范围。如果在子例程/函数中定义,则它仅在该子例程/函数中可见。如果位于顶部,则该表单/报告/模块中的所有 sou/函数都可以看到它。如果您声明它在模块中是全局的,那么它将在任何地方都可见。
所以问题是你为什么问?
Yes you can so long as you don't expect the variable to be pointing to two recordsets.
However the question is why would you? What would you expect to save? Resources? Not a big deal. Also code readability would suffer. If you a week from now or someone else later are looking at your code they might not realize what is going on. Thus I'd suggest a recordset variable per table/query.
Also there is the scope of the variable. If defined in a subroutine/function then it's visible only in that sub/function. If at the top it will be visible to all sou/function in that form/report/module. If you state that it's global while in a module then it will be visible everywhere.
So the question is why do you ask?
是的,但在将记录集变量重新分配给另一个记录集之前,必须确保关闭该记录集。这是一个例子:
关于这个问题的许多评论都集中在是否需要将记录集变量设置为Nothing,是否以及何时需要这样做,以及是否还需要在记录集上调用Close释放记录集引用之前的记录集。关于这个主题有一些精彩的评论,分布在有关堆栈溢出的相当多的问题上; 这个特别重要与您的情况相关。我还会引导您阅读这篇知识库文章和这本深入的书籍摘录。
冒着过度简化的风险,我可以这样总结问题:如果 Access 引用计数工作良好,则无需担心通过将引用设置为
Nothing
来显式释放引用,也无需显式关闭记录集。然而,实践经验告诉我们,考虑到 Access 的行为,这两个习惯都应该成为 VBA 最佳实践编码的一部分。Yes, but you must be sure to close the recordset before you re-assign the recordset variable to another recordset. Here is an example:
Many of the comments on this question have focused on the need to set the recordset variable to
Nothing
, whether and when this is necessary, and whether it is also necessary to call Close on the recordset before releasing the recordset reference. There is some excellent commentary on this topic spread out accross quite a few questions on stack overflow; this one is particularly relevant to your situation. I would also direct you to this knowledgebase article and this in-depth book excerpt.At risk of oversimplifying, I can summarize the issue this way: if Access reference counting worked well, it would not be necessary to worry about explicitly releasing references by setting them to
Nothing
, nor explicitly closing recordsets. Howerver, practical experience tells us that, given the behavior of Access, both of these habits should be part of best practice coding for VBA.