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
Related
I make a code then ask the user where he wants to put a text file created from an excel sheet.
if the selected folder is named formatted file, then a file should create. if the folder formatted file doesn't exist, the code should create a file named formatted Files and then create the text file in it.
the text file contains 4 columns of data from excel.
For now, the folder is created in the right place. the code is update with the correct solution.
if there's a way to simplify my code let me know!!
Here's my actual code:
Sub register_formated_data()
'
' register_formated_data Macro
'
Dim order As Object
Dim Folder As Object
Dim Folder_path As String
Dim lastrow As Long
Dim fSo As Object
Dim myFile As Object
FolderName = "Formated Files"
Filename = "formated" & Right(Sheets(8).Cells(12, 6).Value, InStr(File_path, "\"))
Dim FL As String ' FL is for file location
Sheets(8).Cells(12, 12).Value = ""
With Application.FileDialog(msoFileDialogFolderPicker) '
.Title = "Select where you want the folder to be" 'Open the file explorer
.InitialFileName = ThisWorkbook.path & "\" 'for you to select
.InitialView = msoFileDialogViewDetails 'the file you want
.AllowMultiSelect = True 'to add the txt file
.Show '
On Error GoTo PROC_EXIT
If Not .SelectedItems(1) = vbNullString Then FL = .SelectedItems(1)
End With
Sheets(8).Cells(12, 12).Value = FL
Folder_path = FL + "\" + FolderName
Set fSo = CreateObject("Scripting.FileSystemObject")
If Not fSo.FolderExists(Folder_path) Then
fSo.CreateFolder (Folder_path)
If fSo.FolderExists(Folder_path) Then
Set fSo = CreateObject("Scripting.FileSystemObject")
Set myFile = fSo.CreateTextFile(Folder_path + "\" + Filename, True)
myFile.WriteLine "Error"
myFile.Close
Set fSo = Nothing
End If
Else
If fSo.FolderExists(Folder_path) Then
Set fSo = CreateObject("Scripting.FileSystemObject")
Set myFile = fSo.CreateTextFile(Folder_path + "\" + Filename, True)
myFile.WriteLine "Error"
myFile.Close
Set fSo = Nothing
End If
End If
PROC_EXIT:
End Sub
As FL is picked using a FileDialog, it seems you are trying to create folder FL when it already exists.
Using
fSo.CreateFolder(FL).Name = FolderName
is equivalent to
folder = fSo.CreateFolder(FL)
folder.Name = FolderName
So you need to substitute it by fSo.CreateFolder(FolderName).
The corrected code block is then:
Set fSo = CreateObject("Scripting.FileSystemObject")
If Not fSo.FolderExists(Folder_path) Then
fSo.CreateFolder(Folder_path)
If fSo.FolderExists(Folder_path) Then
Set fSo = CreateObject("Scripting.FileSystemObject")
Set myFile = fSo.CreateTextFile(Folder_path + "\" + Filename, True)
myFile.WriteLine "Error"
myFile.Close
Set fSo = Nothing
End If
End If
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
I'm preparing a code which would every month help users rename specific string in multiple files.
Example: from "Jan" to "Feb", from "Bank" to "Cash", from "Test" to "Sharp" etc. (Bank Statement Jan.xls -> JPM Statement Jan.xls, Form test.xls -> Form sharp.xls, etc.)
I use a function to populate files from all folders and also subfolder picked up a FileDialog, then I prompt the user to InputBox string to be found and string to be replaced in the file name.
Sub testrenametest()
Dim filedlg As FileDialog
Dim xPath As String
Dim fileList As Object
Dim vFile As Variant
Dim FindTerm As String, ReplaceTerm As String, NewFileName As String
Set filedlg = Application.FileDialog(msoFileDialogFolderPicker)
With filedlg
.Title = "Please select folder"
.InitialFileName = ThisWorkbook.Path
If .Show <> -1 Then End
xPath = .SelectedItems(1) & "\"
End With
FindTerm = InputBox("Find string:") ReplaceTerm = InputBox("Replace with:")
Set fileList = getFileList(xPath)
For Each vFile In fileList
If vFile Like "*" & FindTerm & "*" Then
NewFileName = Replace(vFile, FindTerm, ReplaceTerm)
Name vFile As NewFileName
End If
Next vFile
End Sub
Function getFileList(Path As String, Optional FileFilter As String = "*.*", Optional fso As Object, Optional list As Object) As Object
Dim BaseFolder As Object, oFile As Object
If fso Is Nothing Then
Set fso = CreateObject("Scripting.FileSystemObject")
Set list = CreateObject("System.Collections.ArrayList")
End If
If Not Right(Path, 1) = "\" Then Path = Path & "\"
If Len(Dir(Path, vbDirectory)) = 0 Then
MsgBox "You need to browse folder first!"
End
End If
Set BaseFolder = fso.GetFolder(Path)
For Each oFile In BaseFolder.SubFolders
getFileList oFile.Path, FileFilter, fso, list
Next
For Each oFile In BaseFolder.Files
If oFile.Path Like FileFilter Then list.Add oFile.Path
Next
Set getFileList = list
End Function
It works for some strings like month names but for instance for "test" or "bank" doesn't. It says Run-time error 53 File not found on line Name vFile As NewFileName, but the file exists. Sorry for inputting the whole code, but I am unable to pinpoint where might be a problem.
Your problem probably lies in the fact that it is attempting to rename a file inside the loop that no longer exists with that name. Condition the rename by first double-checking to make sure the file still exists.
For Each vFile In fileList
If vFile Like "*" & FindTerm & "*" Then
NewFileName = Replace(vFile, FindTerm, ReplaceTerm)
If Dir$(vFile) <> "" Then
Name vFile As NewFileName
End If
End If
Next vFile
Edit: after additional feedback was provided that the problem is that the replaced string was also found in the path, I suggest the following fix:
For Each vFileSpec In fileList
vPath = Left(vFile, InstrRev(vFileSpec, "\") - 1)
vFile = Mid(vFileSpec, Len(vPath) + 1)
If vFile Like "*" & FindTerm & "*" Then
NewFileName = Replace(vFile, FindTerm, ReplaceTerm)
Name vFileSpec As vPath + "\" + NewFileName
End If
Next vFile
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
Can anyone please review code below and tell me where am I going wrong?
Basically what I am trying to achieve, user inputs name in the Column A, then will click upload button (same row, column F), excel would create a folder using name from Column A, via filedialog window user will select multiple files which should be copied to newly created folder, finally excel would also additionally create path to the folder (saved in column D) and stamp the date (column E).
Current problems:
Fails to copy multiple files, currently I can only copy one file
File is copied to parent folder of newly created folders, basically
fails to copy to newly created folder itself.
My code:
Sub Button1_Click()
Dim objFSO As Object
Dim objFile As Object
Dim openDialog As FileDialog
Dim Foldername As String
Dim Path As String
Dim Newpath As String
Dim i As Integer
Dim myfile As String
Dim myfilePath As String
Foldername = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -5).Value
Path = "C:\Test\"
Set openDialog = Application.FileDialog(msoFileDialogFilePicker)
openDialog.AllowMultiSelect = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
For i = 1 To openDialog.SelectedItems.Count
myfile = openDialog.SelectedItems.Item(i)
Next
If openDialog.Show = -1 Then
If Dir(Path & Foldername, vbDirectory) = "" Then
MkDir Path & Foldername
End If
objFSO.CopyFile myfile, Path
ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -2).Hyperlinks.Add ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -2), Address:=Path & Foldername, TextToDisplay:="Open Folder"
ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -1).Value = Format(Now, "MM/dd/yyyy")
MsgBox "Files were successfully copied"
End If
End Sub
Your For loop was in the wrong place. This is why you were not able to loop through every file and copy it.
You have this problem, because you used objFSO.CopyFile myfile, Path instead of the newly created folder name. I changed that part with this: objFSO.CopyFile myfile, Path & Foldername & "\" . Note that Path & Foldername is not enough, as you need to have \ at the end.
The working code:
Sub Button1_Click()
Dim objFSO As Object
Dim objFile As Object
Dim openDialog As FileDialog
Dim Foldername As String
Dim Path As String
Dim Newpath As String
Dim i As Integer
Dim myfile As String
Dim myfilePath As String
Foldername = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -5).Value
Path = "C:\Test\"
Set openDialog = Application.FileDialog(msoFileDialogFilePicker)
openDialog.AllowMultiSelect = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
If openDialog.Show = -1 Then
If Dir(Path & Foldername, vbDirectory) = "" Then
MkDir Path & Foldername
End If
For i = 1 To openDialog.SelectedItems.Count
myfile = openDialog.SelectedItems.Item(i)
objFSO.CopyFile myfile, Path & Foldername & "\"
Next
ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -2).Hyperlinks.Add ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -2), Address:=Path & Foldername, TextToDisplay:="Open Folder"
ActiveSheet.Shapes(Application.Caller).TopLeftCell.Offset(0, -1).Value = Format(Now, "MM/dd/yyyy")
MsgBox "Files were successfully copied"
End If
Set objFSO = Nothing
Set openDialog = Nothing
End Sub