PDA

View Full Version : Run-time error 424: Object Required



bassnsjp
07-06-2013, 10:58 AM
I found a macro online to get files from a particular directory and all its subdirectories. Getting the files from the parent directory is not a problem. Attempting to get the filenames from the next level directory is where I get the object required error message. Actually it is this line:
Set objFolder = objFSO.GetFolder(SubFolderName)
I've hardcoded SubFolderName as well as allowing the system to acquire the pathname (SubFolder.path) and I get the same results. What is odd is that the same line is used in the main routine and works with no problem. The debug.print just before the Set command displays the correct pathname. Any assistance would be greatly appreciated thank you in advance.

Here is the code:

Sub Getfilesnsubf()
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\bassmaster\Documents\TestFindnReplaceData"
' objStartFolder = InputBox("Enter pathname: ", "Path to search")
If (Right$(objStartFolder, 1)) <> "\" Then
objStartFolder = objStartFolder & "\"
End If
Set objFolder = objFSO.GetFolder(objStartFolder)
Debug.Print objFolder.path
Set colFiles = objFolder.Files

For Each objFile In colFiles
Debug.Print "Filename: " & objFile.Name
Next
ShowSubFolders objFSO.GetFolder(objStartFolder)
End Sub

Sub ShowSubFolders(Folder)
Debug.Print " # of subfolders: " & Folder.subfolders.Count
For Each SubFolder In Folder.subfolders
If (Right$(SubFolder.path, 1)) <> "\" Then
SubFolderName = SubFolder.path & "\"
End If

Debug.Print " SubFolder name: " & SubFolderName
Set objFolder = objFSO.GetFolder(SubFolderName)
Set colFiles = objFolder.Files
For Each objFile In colFiles
Debug.Print " Filename in subfolder: " & objFile.Name
Next
ShowSubFolders SubFolder
Next
End Sub

fumei
07-07-2013, 12:56 PM
You say:

"Actually it is this line:
Set objFolder = objFSO.GetFolder(SubFolderName)"

But your code is:
Set objFolder = objFSO.GetFolder(objStartFolder)


BTW, are you using Option Explicit

bassnsjp
07-07-2013, 08:32 PM
No, I'm currently not using Option Explicit.

And no, the error is not occurring on this line. This line works and the macro works in capturing the files within the objStartFolder.

Set objFolder = objFSO.GetFolder(objStartFolder)

The error occurs on this line, when attempting to process the first subfolder.

Set objFolder = objFSO.GetFolder(SubFolderName)

bassnsjp
07-07-2013, 08:46 PM
I set Option Explicit and after going through and defining each variable the subfolder process worked as expected with no changes in the code other than defining the variables. I have always used Option Explicit in the past and will do so henceforth. Thanks for the suggestion and recommendation fumei this has saved me alot of time.

fumei
07-08-2013, 02:07 PM
ALWAYS use Option Explicit. 90% of object required errors can be identified using it. Do you know how to make it automatically be in any new module?