I have excel files with following worksheets.
City1
City2
City3
City4
City5 and so on till 47 sheets
The file destination is "C:\Users\Dell\Desktop\CityData\"
How could I split file into individual sheets and place them in the folders of same names as the name of sheets . The folders do not exist and I want to create the folders automatically. The folders should be created as subfolders of the above destination folder.
Sub SplitSheets()
Const FolName = "C:\Users\Dell\Desktop\CityData\"
Dim ws as worksheet
for each ws in worksheets
ws.copy
Mkdir folname & ws.name
activeworkbook.saveas folname & ws.name & "\" & ws.name & ".xlsm",52
activeworkbook.close
next ws
end sub
You can use this to split a workbook into separate sheets.
Sub Splitbook()
'Updateby20140612
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
You can copy and move files using the code below.
Sub Copy_Folder()
'This example copy all files and subfolders from FromPath to ToPath.
'Note: If ToPath already exist it will overwrite existing files in this folder
'if ToPath not exist it will be made for you.
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "C:\your_from_path\" '<< Change
ToPath = "C:\your_to_path\" '<< Change
'If you want to create a backup of your folder every time you run this macro
'you can create a unique folder with a Date/Time stamp.
'ToPath = "C:\your_to_path\" & Format(Now, "yyyy-mm-dd h-mm-ss")
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
You could certainly make it more dynamic, if you want to sweep multiple files into multiple different folders. I think the best way to do that would be to list the folders in a column, and then loop through that list of items. Something like this would do the trick.
Dim r As Range '-- if you don't declare it as a range type you get a variant type as default
Dim c As Range '-- this is used to store the single cell in the For Each loop
Set r = Range("A1:B10") '-- substitute your range as per your example
For Each c In r '-- you could also use r.cells
MsgBox c.Value '-- pass to your function instead of a call to the Message Box
Next
Related
I am trying to go through a number of folders with files in side of them. Extract some data from the same range in each of the files and put it on the next blank row within my master spreadsheet. This is called Wb in the code. The code is looping through a folder with subfolders inside.
Sub LoopFolders()
' Declaring variables
Dim myFolder As String
Dim mySubFolder As String
Dim myFile As String
Dim collSubFolders As New Collection
Dim myItem As Variant ' This means that excel will decide what kind of variable it is
Dim wbk As Workbook
Dim Wb As Workbook
Set Wb = ThisWorkbook
' set parent folder with trailing backslash
myFolder = "F:\Documents\Ad-hoc\Loop\"
'Retrieve first sub-folder
' * is the wildcard character
mySubFolder = Dir(myFolder & "*", vbDirectory)
Application.ScreenUpdating = False
'Do While Not mySubFolder = ""
Do While mySubFolder <> ""
Select Case mySubFolder
Case ".", ".." ' . refers to current folder, .. refers to the parent folder
' ignore current folder or parent folder
Case Else
' Add to collection called collSubFolders
'collSubFolders.Add Item:=mySubFolder, Key:=mySubFolder
collSubFolders.Add Item:=mySubFolder
End Select
' Get next entry
mySubFolder = Dir
Loop
' Loop through the collection
For Each myItem In collSubFolders
' Loop through Excel workbooks (with any extension) in subfolder
myFile = Dir(myFolder & myItem & "\*.xls*")
Do While myFile <> ""
' Open workbook
DoEvents
Set wbk = Workbooks.Open(Filename:=myFolder & myItem & "\" & myFile)
' Copy data from the opened workbook
' starting from row 2 and column 1 to row 3 and column 2 and copying it
ActiveSheet.Range(Cells(2, 1), Cells(3, 2)).Copy
---here the code breaks and an error 400 is shown----
' Close opened workbook without saving any changes
wbk.Close SaveChanges:=False
Wb.Activate
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
ActiveWorkbook.Save
Application.CutCopyMode = False
myFile = Dir
Loop
Next myItem
Application.ScreenUpdating = True
End Sub
I've spent some time trying to work out why this might be the case. One thing I found was that when I hover my mouse over the wbk variable it shows nothing even after I have f8'ed through it. The document does open but, after that when it is asked to locate the range on the new active file it cannot cope. Does anyone know why this might be the case?
Also note: the looping through the folders works fine and I can see that by going through it step by step. It is the part I mentioned above that although seems simple seems to not be working.
use:
debug.print myFolder & myItem & "\" & myFile
it is most likely that your path is wrong.
My guess would be that you have a problem with: myFile
Because first you execute:
myFile = Dir(myFolder & myItem & "\*.xls*") and then you execute:
Filename:=myFolder & myItem & "\" & myFile
Which translates into:
Filename:=myFolder & myItem & "\" & Dir(myFolder & myItem & "\*.xls*")
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
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...
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)
my goal is to move specified folders and their contents outof an existing location into a new folder path labeled "Archive". There are about 1000 folders out of 2000 I need moved to this new location. I have a .xlsx file that contains the file paths of each folder that needs moving, listed in column A of the Excel worksheet. I would like my macro to look at the Excel file, read the folder path, move that folder and its contents to a new destination. Repeat through the Excel list until it reaches a blank, then it's considered "Done!"
Here is the code I have found so far (see below). This code will move one folder from one path to another path. I need to enhance this to read each path from my Excel file; I just don't know what that part of the command should look like.
Code and any notes with the code are greatly appreciated! Thank you!
Sub Move_Rename_Folder()
'This example move the folder from FromPath to ToPath.
Dim fso As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "Q:\Corporate-Shares\...\Test folder 1" '<< Change
ToPath = "Q:\Corporate-Shares\...\Test Archive Folder" '<< Change
'Note: It is not possible to use a folder that exist in ToPath
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
If fso.FolderExists(ToPath) = True Then
MsgBox ToPath & " exist, not possible to move to a existing folder"
Exit Sub
End If
fso.MoveFolder Source:=FromPath, Destination:=ToPath
MsgBox "The folder is moved from " & FromPath & " to " & ToPath
End Sub
Please test this code in a test folder before working with your original files. Create copies or dummy files, any failure can damage your existing files....
First, separate this move function taking the name and destination of the path:
Sub Move_Rename_Folder(FromPath as string, ToPath as string)
'to do these two lines, go to tools, references and add Microsoft.Scripting.Runtime
'it's a lot easier to work like this
Dim fso As FileSystemObject
Set fso = new FileSystemObject
'you don't need to set paths anymore, they come as the arguments for this sub
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
If fso.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If fso.FolderExists(ToPath) = True Then
MsgBox ToPath & " exist, not possible to move to a existing folder"
Exit Sub
End If
fso.MoveFolder Source:=FromPath, Destination:=ToPath
MsgBox "The folder is moved from " & FromPath & " to " & ToPath
End Sub
Then, create a main Sub to run over the column "B" (from path) and Column "C" (to path), for instance:
Sub MainSub()
Dim CurrentFrom as Range, CurrentTo as Range
'get B2, assuming your B1 is a header, not a folder
Set CurrentFrom = ThisWorkbook.Worksheets("yoursheetname").Range("B2")
'get C2, assuming your C1 is a header
Set CurrentTo = ThisWorkbook.Worksheets("yoursheetname").Range("C2")
'get the actual values - paths - from cells
Dim ToPath as string, FromPath as string
ToPath = CurrentTo.value
FromPath = CurrentFrom.Value
'loop while your current frompath is not empty
Do while FromPath <> ""
'calls the move function from frompath to topath
Call Move_Rename_Folder(FromPath, ToPath)
'offsets the cells one row down
Set CurrentFrom = CurrentFrom.Offset(1,0)
Set CurrentTo = CurrentTo.Offset(1,0)
'gets the values of the new cells
FromPath = CurrentFrom.Value
ToPath = CurrentTo.Value
Loop
End Sub