|
-
Mar 25th, 2005, 12:13 PM
#1
Thread Starter
Hyperactive Member
FileSystemObject declaring FYI...
just thought i'd post this.. hope it's usefull...from VBA developers handbook...
Needs "Microsoft Scripting Runtime" Library Referenced (SCRRUN.DLL)
Declaring and Instantiating in One Step.
It's tempting to declare and instantiate the FileSystemObject in the same line of code (using the "As New" syntax), and you'll see this done often in other publications. As we've mentioned in other places throughout this book, there's generally nothing to be gained by collapsing the two lines down into one. That is, you'll see this line of code:
Dim fso As New Scripting.FileSystemObject
instead of the two-line version:
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
When you collapse these two lines together, you cause two problems:
• VBA can't tell when it should instantiate the object (it only instantiates the object when you first use it), so VBA must insert checks throughout your code to see if it's time to instantiate the object. This slows down your application's execution.
• If you collapse the two lines into one, you won't be able to compare your variable to Nothing—the moment you try, VBA will instantiate the object (because it thinks you now want to use the object, whether it had already been instantiated), in which case it won't be Nothing anymore. That is, code like this will always instantiate the object referred to by fso, even though it ought not, and the code inside the If Then statement will never run:
Dim fso As New Scripting.FileSystemObject
' Later in your code...
If fso Is Nothing Then
' Too late! This code will never run.
End If
We can only think of one good reason to use the combined declaration/instantiation: if you're writing code and want to test out methods and properties of an object in the Immediate window, it's useful to temporarily create an object in a standard module, like this: Public fso As New Scripting.FileSystemObject
Then, at any time, you can open the Immediate window and work with methods and properties of fso. Other than this, we think you're better off using two lines of code for declaration and instantiation of any object.
-
Mar 25th, 2005, 02:04 PM
#2
Re: FileSystemObject declaring FYI...
The above apply to all objects, not just FileSystemObject. Declaring the object with the New keyword on the same line makes the object approx. 15% slower to call.
-
Mar 25th, 2005, 03:48 PM
#3
-
Mar 25th, 2005, 04:17 PM
#4
Re: FileSystemObject declaring FYI...
Thanks for the info. I have never heard this before.
After checking the validity of the claims, I should probably go back and rewrite some code.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|