VBA copy paste all files in a folder - excel

My macro is running well since 2 months but now I need some help for another issue.
We are running an controller on our server which is sending mails to our customer with attached pdf. Now this controller and my macro are running sometimes at the same time and when my macro is creating pdfs the controller wants to send it but is not able to do so because its already in creation.
Now I thought the macro could save pdf into another folder and after that it will copy paste all files into the right folder for sending.
My code is this:
Function Copy()
Dim MyFile2 As Sting
Dim myPath2 As String, myPath3 As String
myPath2 = "L:\Host_Export\Pdf-Kundenmail\Test\"
myPath3 = "L:\Host_Export\Pdf-Kundenmail\"
MyFile2 = Dir(myPath2 & "*.*")
Do
If MyFile2 = "" Then Exit Do
FileCopy myPath2 & MyFile2, myPath3 & MyFile2
End If
myFile2 = Dir
Loop
End Function
But if I run it there is an error: error on compilation userdefined typ could not be defined. like this: https://i0.wp.com/www.port135.com/wp-content/uploads/2012/08/error1-1.png.
I alredy googled but don't get it how to set up or import something to fix this issue.

Your code won't work because as #user3598756 said, you spelled string incorrectly. To improve your form though, use a do while loop to combine the if and do statements like so:
Function Copy()
Dim MyFile2 As String
Dim myPath2 As String, myPath3 As String
myPath2 = "L:\Host_Export\Pdf-Kundenmail\Test\"
myPath3 = "L:\Host_Export\Pdf-Kundenmail\"
MyFile2 = Dir(myPath2 & "*.*")
Do while MyFile2 <> ""
FileCopy myPath2 & MyFile2, myPath3 & MyFile2
myFile2 = Dir
Loop
End Function

Following sub will copy all files from source folder to destination folder.
Sub AllFiles()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "C:\Users\Alam\Music\Awlad Hossain" 'Souece Folder
ToPath = "C:\MyExcelFiles" 'Destination folder
If Right(FromPath, 1) = "\" Then
FromPath = Left(FromPath, Len(FromPath) - 1)
End If
If Right(ToPath, 1) = "\" Then
ToPath = Left(ToPath, Len(ToPath) - 1)
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFolder Source:=FromPath, Destination:=ToPath
MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath
End Sub
More details here:

Related

list of folder from source folders to destination folders copy vba

I have list of folder list as source path and destination path
I tried to use below codes but cannot understand how to loop in list as below one by one. I need to delete destination folders first, then copy from source folder.
c:\a
c:\b
c:\c
to
D:\a
D:\b
d:\c
Code:
Sub Copy_Certain_Files_In_Folder()
'This example copy all Excel files from FromPath to ToPath.
'Note: If the files in ToPath already exist it will overwrite
'existing files in this folder
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
FromPath = "C:\Users\Ron\Data" '<< Change
ToPath = "C:\Users\Ron\Test" '<< Change
FileExt = "*.xl*" '<< Change
'You can use *.* for all files or *.doc for Word files
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If FSO.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End Sub
The code that you've copied in from Ron de Bruin's Excel Automation site really deals with a whole folder. What I expect you're looking for is a loop to provide a wrapper, which provides access to the individual sub-folder first. Then you can use the code above and add your delete logic, etc. Try this (I use early binding so add reference to script library if you don't already have it.):
Option Explicit
Public Sub CopyFolders(SourceFolderName As String)
Dim fso As New FileSystemObject
Dim SourceFolder As Folder
Dim SourceSubFolder As Folder
Set SourceFolder = fso.GetFolder(SourceFolderName)
For Each SourceSubFolder In SourceFolder.SubFolders
' UPDATE AND PUT YOUR CODE TO COPY SPECIFIC FOLDERS IN HERE
Debug.Print SourceSubFolder.Name
Next
End Sub
ref: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/subfolders-property

how to open xlsm file from specific subfolder using VBA?

I am working on macro that takes the path from clipboard, goes through each folder and subfolder in this path, opens xlsm file in finance subfolder and deletes KPI sheet. Below you can find the folder structure in my path:
P:\main folder\project folder\finance subfolder\
P:\main folder\project folder\brief subfolder\
P:\main folder\project folder\production subfolder\
P:\main folder\project folder\delivery subfolder\
P:\main folder\project folder\feedback subfolder\
Basically, I copy "P:\main folder\" and my macro goes through all project folders and all subfolders. I want to optimise this process and write a code that goes through all project folders in main folder but then goes only to finance subfolder and looks for xlsm files. I've tried to use the code that was posted here but it works only if I put "P:\main folder\project folder\" path not if I put "P:\main folder\" path.
As far as I see the reason is that my macro is looking for finance subfolder not in project folder but in main folder but this is only my guess. Below you can find the code:
Sub test_macro()
Dim oLibrary As Object
Dim srcFolder As Object
Dim folderName As String
Dim clipboard As MSForms.DataObject
Dim CopiedText As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
CopiedText = clipboard.GetText
folderName = CopiedText
If StrPtr(folderName) = 0 Then
Exit Sub
End If
Set oLibrary = CreateObject("Scripting.FileSystemObject")
Merge_Rows oLibrary.GetFolder(folderName)
End Sub
Sub Merge_Rows(srcFolder As Object)
Dim srcSubFolder As Object
Dim srcFile As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
For Each srcSubFolder In srcFolder.SubFolders
If Split(srcSubFolder, "\")(UBound(Split(srcSubFolder, "\"))) = "1_FINANCE" Then '<-- my guess is that here is the problem but not sure how to fix it
Merge_Rows srcSubFolder
End If
Next
For Each srcFile In srcFolder.Files
If LCase(srcFile.Name) Like "*.xlsm" Then
Set wbkSource = Workbooks.Open(srcFile)
On Error Resume Next
Application.DisplayAlerts = False
wbkSource.Sheets("KPI").Delete
Application.DisplayAlerts = True
wbkSource.Close SaveChanges:=True
End If
Next
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
How can I change a code so it goes through each project folder but then goes only to finance subfolder and omits others?
Here is my idea, but it is done for 2 level subfolder (if I understood the task properly):
Sub Merge_Rows()
Dim srcFolder As Object
Dim srcSubFolder As Object
Dim srcSubSubFolder As Object
Dim srcFile As Object
Dim oLibrary As Object
' This is my testing vars
Dim FolderName As String
FolderName = "P:\"
'''''''''
' will need it as I'm not passing the folder to sub
Set oLibrary = CreateObject("Scripting.FileSystemObject")
Set srcFolder = oLibrary.getfolder(FolderName)
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' added for testing purposes
Dim fileCounter As Long
Debug.Print "-----------------" & "Source folder: " & FolderName & "--------------------------------"
Debug.Print Chr(10)
For Each srcSubFolder In srcFolder.Subfolders ' going to subfolders
' print the level 1 subfolder name, which should be a project folder
For Each srcSubSubFolder In srcSubFolder.Subfolders ' going to sub-subfolder
' print the level 2 subfolder name, which should be a project folder subfolder
Debug.Print "----------- Current SubFolder is: " & FolderName & srcSubFolder.Name & "-----------------"
If UCase(srcSubSubFolder.Name) Like "*FINANCE*" Then '<--!! put proper pattern
' go through it at once
For Each srcFile In srcSubSubFolder.Files
Debug.Print "----------------- Current SubSubFolder is: " & FolderName & srcSubFolder.Name & "\" & srcSubSubFolder.Name & "---------------------"
If LCase(srcFile.Name) Like "*.xlsm" Then
Debug.Print srcFile.Name
fileCounter = fileCounter + 1
' Your code here
End If
Next
End If
If Not fileCounter = 0 Then
Debug.Print "There were " & fileCounter & " .xlsm files in " & FolderName & srcSubFolder.Name & "\" & srcSubSubFolder.Name
fileCounter = 0
Else
Debug.Print "The search of .xlsm files in " & FolderName & srcSubFolder.Name & "\" & srcSubSubFolder.Name & " was not performed"
End If
Debug.Print "-----------------" & "End of current SubSubFolder: " & FolderName & srcSubFolder.Name & "\" & srcSubSubFolder.Name & "---------------------"
Next
Debug.Print "-----------------" & "End current SubFolder: " & FolderName & srcSubFolder.Name & "---------------------"
Debug.Print Chr(10) & Chr(10)
Next
Debug.Print "<-----------------" & "End Source Folder" & "--------------------->"
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
And it looks like this
If it fits - you need to fix it for your solution, it's just a thoughts :)
Update per OPs comment
I've updated code with some more Debug.Print lines
Here the file tree that I've created for testing:
Each folder has a "Book3.xlsm" file in it.
Here is the result of the updated script:
Try to run at least one iteration of project folder and check the immediate window.

Copying 1 file into multiple subdirectories

I have found one code snippet that successfully copies 1 file to one specific directory. However what I am trying to piece together is a way to copy one file into hundreds of subdirectories. I have also found code that recursively cycles through subfolders and allows you to take action upon the files in the subfolders. Surely there must be a mash up of these two codes that would allow me to copy the 1 file into numerous subdirectories.
If this is not possible I have working code for a command prompt.
Sub Copy_Certain_Files_In_Folder()
'This example copy all Excel files from FromPath to ToPath.
'Note: If the files in ToPath already exist it will overwrite
'existing files in this folder
Dim fso As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
'FromPath = "C:\Users\Ron\Data" '<< Change
'ToPath = "C:\Users\Ron\Test" '<< Change
FileExt = "*.pdf" '<< Change
'You can use *.* for all files or *.doc for Word files
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set fso = CreateObject("scripting.filesystemobject")
If fso.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If fso.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
fso.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End Sub
Code that cycles through subfolders:
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
Any advice is welcome!
Try the following code:
'*****************************************************
' FUNCTION HEADER: Put_A_File_In_All_Subfolders
'
' Purpose: Looks for the specified file, and if it exists it
' puts the file in all subfolders of the target path.
'
' Inputs:
' blnFirstIteration: True / false for whether this is the first function call
' strFromPath As String: The path where the file to copy is located.
' strToPath As String: The path where the destination folder tree exists.
' strFileToCopy: The filename to copy.
'*****************************************************
Sub Put_A_File_In_All_Subfolders( _
blnFirstIteration As Boolean, _
strFromPath As String, _
strToPath As String, _
strFileToCopy As String)
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim blnEverythingIsValid As Boolean
blnEverythingIsValid = True
'If this is the first run, check to make sure the initial file
'exists at that path, else throw error messages:
If blnFirstIteration Then
If Right(strFromPath, 1) <> "\" Then
strFromPath = strFromPath & "\"
End If
If fso.FolderExists(strFromPath) = False Then
MsgBox strFromPath & " doesn't exist"
blnEverythingIsValid = False
Else
If Not fso.FileExists(strFromPath & strFileToCopy) Then
MsgBox strFileToCopy & " doesn't exist in " & strFromPath
blnEverythingIsValid = False
End If
End If
If fso.FolderExists(strToPath) = False Then
MsgBox strToPath & " doesn't exist"
blnEverythingIsValid = False
End If
End If
If blnEverythingIsValid Then
If Right(strToPath, 1) <> "\" Then
strToPath = strToPath & "\"
End If
'Copy the file to the destination folder
fso.CopyFile (strFromPath & strFileToCopy), strToPath, True
'Run the sub recursively for each subfolder
Dim vntSubFolder As Variant
Dim currentFolder As Scripting.Folder
Set currentFolder = fso.GetFolder(strToPath)
'Check to see if there are subfolders
If currentFolder.SubFolders.Count > 0 Then
For Each vntSubFolder In currentFolder.SubFolders
'Dim fsoSubFolder As Scripting.Folder
'Set fsoSubFolder = currentFolder.SubFolders.item(vntSubFolder)
Dim strSubFolderPath As String
strSubFolderPath = vntSubFolder.Path
Put_A_File_In_All_Subfolders False, strFromPath, strSubFolderPath, strFileToCopy
Next vntSubFolder
End If
Else
Set fso = Nothing
Exit Sub
End If
Set fso = Nothing
End Sub
You can call it using:
Put_A_File_In_All_Subfolders True, "C:\PathWithFile\", "C:\RootDestinationFolder", "Filename.ext"
I mashed that up quickly, so please test before using widely...

How to use multiple selections from VBA Userform Multiselect Listbox in path

I have created a VBA userform, by manipulating code i found from a website, for coworkers to transfer files from selected folder from one listbox to another folder in a second listbox. The folders that populate in the listboxes change daily. It works fine for both listboxes with fmSingleSelect but i cannot figure out how to run it properly with a fmMultiSelect property on the second listbox (Yes, i changed the property to fmMultiSelect on the second listbox).
It would save time to be able to multiselect the projects folder and run the transfers simultaneously.
Below is the code for single select and commented out some code i was working with for multiselect
Also an image is below code
Thanks
Private Sub CmdBtn_transfer_Click()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
Dim Value As String
Dim i As Integer
FromPath = "C:\Users\us-lcn-dataprep03\Desktop\Production files\" & (Me.ListBox1) '<< Change
ToPath = "\\bego.hb\MED_PRODUCTION\USA_Datapreparation\" & (Me.ListBox2) '<< Change
' For i = 0 To ListBox2.Items.Count - 1
' If ListBox2.Items(i).Selected = True Then
' Val = ListBox2.Items(i).Value
' End If
'Next i
FileExt = "*.sli*" '<< Change
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If FSO.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End Sub
Userform list boxes
The following code is a "minimal change" alteration to your code so that it should handle copying the files from one directory to multiple directories:
Private Sub CmdBtn_transfer_Click()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
Dim Value As String
Dim i As Integer
FromPath = "C:\Users\us-lcn-dataprep03\Desktop\Production files\" & (Me.ListBox1) '<< Change
FileExt = "*.sli*" '<< Change
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i) Then
ToPath = "\\bego.hb\MED_PRODUCTION\USA_Datapreparation\" & (Me.ListBox2.List(i)) '<< Change
If Right(ToPath, 1) <> "\" Then
ToPath = ToPath & "\"
End If
If FSO.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End If
Next i
End Sub
All I did was move your commented out code re looping through the selected items in ListBox2 so that it was wrapped around the parts of the code which are affected by the ToPath. (Note: The MsgBox is within the loop - you may wish to move it outside the loop but, if you do, you may want to make the message more generic - e.g. "Your files have been moved as requested".)
I also corrected some mistakes in your commented code:
ListBox2.Items.Count should be ListBox2.ListCount
ListBox2.Items(i).Selected should be ListBox2.Selected(i)
ListBox2.Items(i).Value should be ListBox2.List(i)

Copy and Rename Folder using VBA

I have a folder with numerous linked workbooks. I would like to store a master copy of it within the C:\ drive. When someone needs to use it they would click on the below macro to copy the folder, ask what the new name will be and place it on the desktop for use. The below code cycles through but does not place the folder on the desktop. It just seems to disappear and does not copy the original
Hoping someone can help??
Sub Copy_Folder()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim strName As String
FromPath = "C:\v4 Master Operations Folder"
ToPath = "C:\Users\Owner\Desktop"
Application.CutCopyMode = False
Reenter:
strName = InputBox(Prompt:="Enter the name of your operation", _
Title:="Operation.", Default:=" ")
If strName = vbNullString Then
MsgBox "Incorrect Entry."
GoTo Reenter
End If
If Right(FromPath, 1) = "\" Then
FromPath = Left(FromPath, Len(FromPath) - 1)
End If
If Right(ToPath, 1) = "\" Then
ToPath = Left(ToPath & strName, Len(ToPath) - 1)
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFolder Source:=FromPath, Destination:=ToPath & strName
MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath & strName
End Sub
It looks like the problem is on this line:
FSO.CopyFolder Source:=FromPath, Destination:=ToPath & strName
You are setting your Destination variable equal to ToPath & strName, so if the user enters "My name" then it would be "C:\Users\Owner\DesktopMy Name". You need to put a slash in there: Destination:=ToPath & "\" & strName

Resources