I have noticed that a lot of code I have found on the internet will have variables defined and set that I would simply avoid...such as:
Dim db as Database
Dim rs as Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset
I would write this as:
Dim rs as Recordset
Set rs = CurrentDB.OpenRecordset
I save 2 lines of code at the top plus one to Set db = Nothing
at the end. Which, over hundreds of subs and functions can really add up...
But is one more preferred over another by most coders? Is there an actual reason to use one or the other? Is there an advantage to actually defining and spelling out the whole thing?? Is there any real savings in doing it my way, other than staving off carpel tunnel for a few more minutes?
In terms of execution, there is no real difference between the two VBA methods. However, the first is a more generic version as the
db
object can be set to either the local DAO database or an external DAO database using the Workspace.OpenDatabase method. The second is a more shortcut version as usually needed recordsets, querydefs, etc. derive from the working, local database. Below are examples of referencing external databases.Short cut version:
Full generic version:
Therefore, should a developer change database environments (i.e., transition from local to external database source) and even workspaces, they can easily change the
set db = ...
line instead of adding this line to the code if developer had originally used only theCurrentDb
namespace.This is a good example of the trade-off decision between efficiency (less scripted lines) and scalability (translatable lines).