Copy folder to another folder in VBA - vba

I want to copy one folder among many folders and paste it to another location. How can I achieve this using VBA?
I am using the below code but it copies all the folders and save it. I just want to copy one folder.
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.CopyFolder Source:=FromPath1, Destination:=ToPath
FromPath1 has many folders. Say a,b,c,d,e. I just want to copy a and save it to ToPath.

Change your FromPath1. For example, instead of "C:\Temp" use "C:\Temp\a"

Related

Converting xls to xlsx and deleting the old file

I am using the following macro to convert an xls file to xlsx. The problem with it is the line that says SaveAs. This creates a second file, one with the original xls extension and the second with the xlsx extension. If I simply say Save, I get an error. How can I either delete the xls file or have the macro do a Save instead of SaveAs? The reason we need to convert the file is so that when we email the file it is smaller in size.
Dim s As String
s = ActiveWorkbook.FullName
s = Replace(s, "xls", "xlsx")
ActiveWorkbook.SaveAs Filename:=s, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
In terms of saving your current file, you have 2 choices: overwrite your current file (with the same type), or generate a new file. This is a limitation (feature?) of Excel, not VBA.
So, to acheive what you want, we will need to do some more work. What we need for this is the FileSystemObject. This basically allows you to interact with the files and directories on your computer through VBA. The first thing we need to do is keep the original file name; This will allow us to delete it by name. From there, we will create the FileSystemObject, and use it to call the DeleteFile method. So, your code should look like
Dim old_name As String, new_name As String
old_name = ActiveWorkbook.FullName
new_name = Replace(old_name, "xls", "xlsx")
ActiveWorkbook.SaveAs Filename:=new_name, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Dim FSO as FileSystemObject
Set FSO = New FileSystemObject
FSO.DeleteFile old_name
Set FSO = Nothing
Note that you will need to set a reference to Microsoft Scripting Runtime in order to create and use a FileSystemObject.

Copy same worksheet in different Excel to one destination Excel file

I have multiple Excel files and they all have the same Worksheet in them named Fixture.
I am trying to copy all of them (they are all in the same folder) and paste them in my destination Excel file under the name of the original Excel file.
For example:
[Excel1]Fixture will be a new worksheet in Main.xlsx named Excel1 after running the VBA. Same with Excel2, Excel3, etc.
Please help!
I suggest you act in four steps:
Create a workbook, e.g. "Collect.xlsx" to collect all "Fixture" sheets
Get your Excel file names and loop through them
In the loop, copy each "Fixture" sheet to your Collect.xlsx
Close and save Collect.xlsx
To 2: You can get the Excel file names either by dir() or by fileDialog:
dir:
http://msdn.microsoft.com/en-us/library/dk008ty4(v=vs.90).aspx
You can use it with or without parameter, thus looping through a
directory. Useful if you want a simple loop, or if you have hundreds of files.
FileDialog: Use the famous FileDialog by Karsten Pries. You can select multiple names
and then loop through them. Download: http://www.kpries.de/download/FileDialog.zip
Your loop might look somehow like this:
...
...
fileDialog.Filter1Suffix = "*.xls"
fileDialog.Filter1Text = "Excel Dokumente"
fileDialog.ShowOpen
fileName = fileDialog.fileName
Do While fileName <> ""
ImportOneSheet fileName ' <<< your own method to collect Fixture
fileName = fileDialog.GetNextFile
Loop
...
If you use dir, just set your ImportOneSheet method in the dir loop.
To 3: Some crucial commands are:
Application.Workbooks.Open (fileName)
Set myExcel = GetObject(, "Excel.Application")
Set importWorkBook = Application.ActiveWorkbook
importWorkBook.Sheets("Fixture").range("A:ZZ").Copy
collectorWorkBook.Sheets(consolidationSheetName).range("A:ZZ").PasteSpecial xlPasteValuesAndNumberFormats, xlPasteSpecialOperationNone, True, False
importWorkBook.Close
These are merely snippets to give you ideas. You might want to find out more about these.
To 4: use the saveAs command: xlam.ActiveWorkbook.SaveAs path, xlOpenXMLWorkbook, , , False, False and the close command: xlam.Workbooks.Close.
For anything remaining, you will find tons of snippets in the net. Good luck :-)

vba, include functions like c++(or many other languages)

I have recently started working on lots of vba/excel work. Coming from python/sas/c++ environment I am having some issues getting comfortable with the methodology.
Realizing I am using same macros copying and pasting from one workbook to another I was hoping to create a library of macros and just like many other languages include these in workbooks I create.
For example. I have a script to create a file:
sub createfile(path as string)
' Create or overwrite the file.
Set fso = CreateObject("scripting.FileSystemObject")
Set a = fso.CreateTextFile(path, True)
end sub
Whenever I write a new macro I want to include this script (or some other script I wrote) instead of copy pasting it.
like
include C:\Directory\script.vb
at the new workbook.
Is there a way to do this so I can be more organized?
Thanks for any input.

Macro to Copy data from specific sheet in many files in one folder to a consolidated file

I am new to Excel macros.
I have a folder having many files.lets say A,B,C
They all have a worksheet named Summary.
I want a new file named Summary
Which iterates through each file and copies the summary worksheet...into separate worksheet in summary file.
The summary file will hv 3 sheets named A,B, C each having its own summary
First, you'll need a list of files. You can use another spreadsheet to hold the list, or you can scan the directory as follows:
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder("C:\temp")
s = ""
For Each fil In fld.Files
s = s & fil.Name & vbCrLf 'a sample of doing something with each fil
'here you can open each workbook using Application.Workbooks.Open
'then, or later, if you like you can close the ones you opened
'by remembering which workbooks were opened before you started.
Next
-- See: http://msdn.microsoft.com/en-us/library/aa242702%28v=vs.60%29
Next, you'll need to create a new workbook, which can be done using
Set newWkb = Application.Workbooks.Add()
-- See: http://msdn.microsoft.com/en-us/library/ff840478.aspx
Now you can use the techniques described by the above posters to copy the worksheet from one workbook to the new one.
For reference, here's some good information on the VBA language. Check out the various Functions, Objects, and Methods, etc.. under the Language Reference: http://msdn.microsoft.com/en-us/library/aa242702%28v=vs.60%29
And here's some good information about the Excel object model: http://msdn.microsoft.com/en-us/library/ff194068

VBA - Copy as Path

I need help with a coding requirement that I've not previously experienced. I just browsed a similar issue raised here a couple of years ago - VBA to Copy files using complete path and file names listed in Excel Object.
My issue is similar but somewhat simpler than the OP.
I have a number of folders that each contain about 100 small .csv files; for each folder I need to copy the path for each file to an open worksheet. Each folder of .csv files has its own associated workbook.
As one example, the open workbook is F:\SM\M400AD.xlsm and the active worksheet is CSV_List. The folder containing the .csv files is F:\SM\M400AD.
Doing it manually, my sequence is then:
Open folder F:\SM\M400AD
Select all
Copy path
Paste to Range("B11") of worksheet CSV_List
When I do it manually, as described above, I get a list that looks like:
"F:\SM\M400AD\AC1.csv"
"F:\SM\M400AD\AC2.csv"
"F:\SM\M400AD\AE.csv"
"F:\SM\M400AD\AF.csv"
"F:\SM\M400AD\AG.csv"
"F:\SM\M400AD\AH1.csv"
"F:\SM\M400AD\AH2.csv"
"F:\SM\M400AD\AJ.csv"
and on down the page until I have a list of 100 paths. This single column list is then pasted into worksheet CSV_List, starting at Range("B11").
I need to automate this and would be grateful if a VBA guru could kindly code this for me.
Such of question has been asked before, for example:
Loop through files in a folder using VBA?
List files in folder and subfolder with path to .txt file
The difference is you want to "automate" it, which means you want to execute code on workbook Open event.
How to achieve that?
Open F:\SM\M400AD.xlsm file.
Go to Code pane (ALT+F11)
Insert new module and copy below code
Option Explicit
Sub EnumCsVFilesInCurrentFolder()
Dim sPath As String, sFileName As String
Dim i As Integer
sPath = ThisWorkbook.Path & "\"
i = 11
Do
If Len(sFileName) = 0 Then GoTo SkipNext
If LCase(Right(sFileName, 4)) = ".csv" Then
'replcae 1 with proper sheet name!
ThisWorkbook.Worksheets(1).Range("B" & i) = sPath & sFileName
i = i + 1
End If
SkipNext:
sFileName = Dir(sPath)
Loop While sFileName <> ""
End Sub
Now, go to ThisWorkbook module and insert below procedure:
Private Sub Workbook_Open()
EnumCsVFilesInCurrentFolder
End Sub
Save and close workbook
The workbook is ready to use. Whenever you open it, EnumCsVFilesInCurrentFolder macro will be executed.
Note: you have to change above code to restrict the number of records.