Open files in a loop using Dir - excel

I want to open a file, copy from it then paste to another document, copy from that and paste back into the opened document.
I converted the file names to strings and it recognizes that but says they don't exist.
Dim StrFile As String
'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile
StrFile = Dir("H:\Open Work book" & "\" & "*.xlsx")
Do While Len(StrFile) > 0
StrFile = Dir
'Opens The File In The folder
Workbooks.Open StrFile
This should open the files in a loop. It says
Sorry, we couldn't find CTM Service Reach.xlsx. Is it possible it was moved renamed or deleted?

When you execute
StrFile = Dir("H:\Open Work book" & "\" & "*.xlsx")
strfile gets filled with the first file matching the pattern. You check that something is returned
Do While Len(StrFile) > 0
but then you change strfile into the next file meeting the pattern - throwing away the first file's name
StrFile = Dir
Then you attempt to open the file without specifying where it is
Workbooks.Open StrFile
what you should be doing is
StrFile = Dir("H:\Open Work book" & "\" & "*.xlsx")
Do While Len(StrFile) > 0
Workbooks.Open "H:\Open Work book" & "\" & StrFile
StrFile = Dir
Loop

I know, you have your solution but, hey, like the Romans used to say: variatio delectat. Here's another way of doing this:
Sub test()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim strDir As String
Dim wkb As Workbook
strDir = "H:\Open Work book\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDir)
For Each objFile In objFolder.Files
If objFSO.GetExtensionName(objFile) = "xlsx" Then
Set wkb = Workbooks.Open(objFile)
// You code here
End If
Next
End Sub

Related

Function Dir() not working as excepted : Error Code 5 : Invalid argument or procedure call

I'm trying to set a macro which will moove file from a certain folder to another one, If this file already exists then it will display a message box if a file from an other folder already exist in a folder. Here is the problem..
I think the first error is here :
StrFile = Dir
Here is the error it display me the error code : 5 Invalid argument or procedure call
And the excepted output of this line code is to go to next file in order to browse all my .Pdf file one per one
Sub MooveFile()
Dim filepath As String
Dim currfile As String
Dim NomFichier As String
Dim Direction As String
Dim StrFile As String
Dim FSO As Object
Dim SourceFileName As String, DestinFileName As String
StrFile = Dir(ActiveWorkbook.Path & "\" & "*.PDF")
Do While Len(StrFile) > 0
Direction = Split(StrFile, " ")(0)
Set FSO = CreateObject("Scripting.Filesystemobject")
SourceFileName = ActiveWorkbook.Path & "\" & StrFile
Set FoundRange = Sheets("Path").Cells.Find(what:=Direction, LookIn:=xlFormulas, lookat:=xlWhole)
If FoundRange Is Nothing Then 'Here is the test if the folder exist : WORKING
On Error Resume Next
MkDir ActiveWorkbook.Path & "\" & Direction
DestinFileName = ActiveWorkbook.Path & "\" & Direction & "\" & StrFile
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
Else 'If Folder exist : WORKING
DestinFileName = ActiveWorkbook.Path & "\" & Direction & "\" & StrFile
If Dir(SourceFileName) <> "" Then 'IF File exist then display the message box : WORKING
Select Case MsgBox("le fichier" & SourceFileName & "existe déjà voulez-vous le remplacer", vbAbortRetryIgnore)
Case vbAbort
' Cancel the operation.
MsgBox "Operation canceled"
Case vbRetry
' Continue the Do loop to try again.
FSO.DeleteFile DestinFileName, True
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
Case vbIgnore
' Take a default action.
GoTo nextline
End Select
Else
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
'FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
nextline:
StrFile = Dir 'This line code is not working at : Error code 5 :Invalid argument or procedure call
Loop 'Fin Boucle
Application.ScreenUpdating = True
End Sub
Did I miss something here ? I already tried StrFile = Dir()
I'm not sure why you are using Dir when you are creating a FileSystemObject?
Although (in my experience) it is slower it is far more robust.
For a start, don't create it as an Object. Put a reference to Windows.Scripting then
Dim FSO As Scripting.FileSystemObject
set FSO= New Scripting.FileSystemObject
Apart from anything else, it will give you the Intellisense which makes life easier.
You can then check for a file/folder with
If FSO.FileExists(myFile) Then
If FSO.FolderExists(myFolder) Then
And start to use collections such as
Dim fi As Scripting.File
For Each fi In FSO.GetFolder(myFolder).Files
Next
Microsoft Reference

How to make Excel VBA wait to unzip all files before continuing

I'm trying to unzip 589 PDF files from one .zip file but upon checking the unzipped files in my destination folder, only 100+ are unzipped. I guess the code does not wait.
I think I got this code from Ron de Bruin but I cannot find the code on how can I make my script to wait for all the files to be extracted before continuing to the next step.
Sub UnzipFile_Click()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim strDate As String
Application.ScreenUpdating = False
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Create the folder name
strDate = Format(Now, " mm-dd-yy")
FileNameFolder = DefPath & "DFM Invoices " & strDate & "\"
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).Items
MsgBox "You may find the unzipped files here: " & FileNameFolder
TextBox1.Value = FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub

Zip each Excel file in a folder separately.

I am currently stuck trying to zip every file in a folder separately. I do not want to zip the folder or zip all the files together. They need to be zipped separately in order for me to traverse the XML folder later and extract images which are going to be OCR'd. My attempt was to use VBA and just change the file extensions
Sub Create_Zip()
Dim FSO As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Const zipDir As String = "\\...\Zip Test"
Set FSO = New FileSystemObject
Set myFolder = FSO.GetFolder(zipDir)
For Each objFile In myFolder.Files
strFilename = objFile.Name
new_strFilename = Replace(strFilename, ".xlsx", ".zip")
Next objFile
End Sub
According to the "immediate window" the string variable "new_strFilename" has the file extension ".zip" but I am not seeing the change in the folder.
You assign the new filename to the variable new_strFilename but not to the actual file.
Since you are getting an error when trying objFile.Name = new_strFilename I assume that property is read-only.
In general if you want to rename a file use the Name function:
Name oldFile As newFile
where oldFile and newFile are strings containing the whole path to a file.
In your example something like this:
For Each objFile In myFolder.Files
strFilename = objFile.Name
new_strFilename = Replace(strFilename, ".xlsx", ".zip")
Name zipDir & "\" & strFilename As zipDir & "\" & new_strFilename
Next objFile
Try to use name A as B .
Sub Create_Zip()
Dim FSO As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Const zipDir As String = "\\...\Zip Test"
Set FSO = New FileSystemObject
Set myFolder = FSO.GetFolder(zipDir)
For Each objFile In myFolder.Files
strFilename = objFile.name
new_strFilename = Replace(strFilename, ".xlsx", ".zip")
Name zipDir & "\" & strFilename As zipDir & "\" & new_strFilename
Next objFile
End Sub

Excel VBA Dir loop fails when open and close command added within loop

I am trying to import data from all Excel files within a directory with the same prefix. Data will be aggregated from these files and written to the master file. I have successfully crafted a do while script that can identify the three test files using DIR with a wildcard. However, when I add the command to open the file (and immediately close it) the do while fails after the first pass after opening and closing the file. Commenting out the open and close commands and the do while loop, loops three times identifying the test files. Ultimately I would like to replace the open / close commands with a call to a sub that will open the files, aggregate the data and write it to the master file. I mention this in case it changes the way to code this. I have searched the forum and found a couple of other ways to accomplish some of my objectives but not all. One example being the wildcard in the filename. Any help is appreciated.
Sub LoopThroughFiles()
Dim strName As String
Dim strPath As String
Dim strFile As String
strPath = ThisWorkbook.Path
strName = "Employee Gross Sales"
strFile = Dir(strPath & "\" & strName & "*")
Do While Len(strFile) > 0
Debug.Print strFile
' Call OpenFile(strPath, strFile) <-- Eventually will replace open / close commands below
Workbooks.Open FileName:=strPath & "\" & Dir(strPath & "\" & strFile)
' Read / Aggregate / Write data code here or in called sub
Workbooks(strFile).Close SaveChanges:=False
strFile = Dir
Loop
End Sub
Sub OpenFile(strPath, strFile)
Dim wbTarget, wbSource As Workbook
Set wbSource = Workbooks.Open(FileName:=strPath & "\" & Dir(strPath & "\" & strFile))
wbSource.Close SaveChanges:=False
End Sub
Your Dir(strPath & "\" & strFile) in the Workbooks.Open command is "overwriting" your original Dir - you should just use strFile at that point.
If you cut your current code down to just the bits that are affected by the Dir, it would look like this:
strFile = Dir(some_string_including_wildcard)
'The above statement returns the first file name matching the wildcarded expression
Do While Len(strFile) > 0
... Dir(specific_filename_being_processed) ...
'The above statement finds the first file name matching the specific filename
'which will obviously be the specific filename
strFile = Dir
'That statement gets the next file name matching the argument last used as
' a parameter to a Dir. As the last argument was a specific file, and there
' are no more files matching that argument (because it contained no wildcards)
' this returns an empty string.
Loop
Your code should be written as:
Sub LoopThroughFiles()
Dim strName As String
Dim strPath As String
Dim strFile As String
strPath = ThisWorkbook.Path
strName = "Employee Gross Sales"
strFile = Dir(strPath & "\" & strName & "*")
Do While Len(strFile) > 0
Debug.Print strFile
' OpenFile strPath, strFile ' <-- Eventually will replace open / close commands below
Workbooks.Open FileName:=strPath & "\" & strFile
' Read / Aggregate / Write data code here or in called sub
Workbooks(strFile).Close SaveChanges:=False
strFile = Dir
Loop
End Sub
Sub OpenFile(strPath As String, strFile As String)
Dim wbTarget As Workbook, wbSource As Workbook
Set wbSource = Workbooks.Open(FileName:=strPath & "\" & strFile)
wbSource.Close SaveChanges:=False
End Sub

Using getfolder function to go to a default folder then select sub-folder

I had used some code I found on here to start trying to convert a big list of Excel CSV files to Excel 2003 format. In the process of converting I wanted to open a default location folder then navigate to the right sub-folder where the CSV files are, however when stepping through the code one of my variables will not populate. My code is below and the variable that won't populate is strDir.
I'm wanting code to populate strDir with the default location + the folder that I pick, however I'm unsure what I need to do to this code to enable it to do that.
Right now I only have the default location hard-coded and when code runs, this location opens. however when I pick the sub-folder how do I record that programatically?
I know what I want to do but how to achieve this in VBA is my question.
Public Sub CSV_to_XLS()
Dim wb As Workbook
Dim strFile As String
Dim strDir As String
Dim strDirCapture As String
'Set base directory for get folder to manipulate csv files
strDirCapture = GetFolder("\\DEVP-APPS-07\File Storgae\1_Pending\")
'strDir = strDirCapture
strDir = strDirCapture & "\"
strFile = Dir(strDir & "*.csv")
MsgBox "String directory path = " & strDirCapture
MsgBox "StrFile = " & strFile
Do While strFile <> ""
'Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
'wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), 56 'UPDATE:
wb.Close True
Set wb = Nothing
strFile = Dir
Loop
End Sub
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Many thanks
Andrew
Update adding slash "\" to end of directory captured seems to have fixed this. Have altered code above to reflect this change.
Try adding these lines after strDir = strDirCapture:
If Right(strDir, 1) <> "\" Then
strDir = strDir & "\"
End If

Resources