I’m attempting to run a code that is meant to loop through all excel files in a folder and copy & transpose information from sheet3 onto sheet1 on a master file. The looping function uses a filepath and the Dir command to return the file location, but presents an error message when instructed to open the file, saying: “Run-time Error 1004: We could not find Testfile.xls. Is it possible it was moved, renamed or deleted?” I don’t understand how the program can correctly identify the file name and yet not be able to locate it.
This is my first attempt to code in VBA and I’ve taken on what seems like a complicated task. I’ve included the code for how the filepath is defined and how the loop function is meant to summon up the first file. When I began working on this code this morning, I was able to open files without any issue; however, after updating my excel (MAC 2017 edition) in order to get access to more tools in the VBA editor, I could no longer open files using the workbooks.open command.
I have tried using the Application.FileDialog(msoFileDialogFolderPicker) command instead of stating the file path, but the dialogue box does not open. I’m not sure if I need to revert to an earlier version of excel or if there is an issue in my syntax that I am overlooking that can explain why my error box can correctly tell me the name of the file but also thinks it isn’t in the folder.
Sub LoopThroughDirectory() Dim MySource As String 'the name for file that data will come from Dim Filepath As String Filepath = "/Users/Victor/Desktop/Clocks/" 'the folder that files are located in MySource = Dir(Filepath) 'define location of source files 'Establish loop Do While Len(MySource) > 0 If MySource = "zzmaster.xlsx" Then Exit Sub End If 'process should loop through all files in the directory until it reaches the master file... 'master file should be the last file in the folder, so loop contains all relevant files 'begin loop Set wb1 = Workbooks.Open(MySource) <--the error generates at this step DoEvents 'Opens source file
The syntax is being run from the zzmaster.xlsx file, which is in a folder on my desktop along with 5 other test files. I’m happy to provide more information if needed. I don’t have the experience with this language to recognize if the error is in the syntax, in my file management, or in my decision to update my Excel.
Dir only returns the filename of each file in the folder. When you try to open it, VBA is looking in the current working directory. To open a file in another location you need to use the full path:
Set wb1 = Workbooks.Open(Filepath + MySource)