Write the content of two Excel files in a third one - vba

I'm very new to vba programming and I would like to know what is the best method to do the following operation : read data from two Excel files (from a particular column of each file) and write this data in a third Excel file, writing the data contained in the first file first then the data contained in the second file. The figure below illustrates what I want to do :
How can I do that on click on a command button, without opening the two first files (I mean I don't want the user to see them).

You need to make so
Workbooks.Open Filename:= "c:\myfile\FILE1.xls"FILE1.xls"
Workbooks.Open Filename:= "c:\myfile\FILE2.xls"
After you open the FILE1.xls and FILE.xls you can create or open FILE3.xls,
in this case we create the FILE3.xls
Dim wb As Workbook
Set wb = Workbooks.Add
After this you read the data in FILE1.xls and FILE2.xls, you can read with WHILE or other LOOP or you read with COPY and PASTE data in new file.
In this case we see the LOOP strategy.
Dim i as Integer
Dim value as String
i=0
value = value = Workbooks("FILE1.xls").Worksheets("sheet1")..Range("B:B").Cells(i, 1)
Workbooks("FILE1.xls").Worksheets("sheet1").Activate
while value <> ""
Workbooks("FILE1.xls").Worksheets(2).Range("A:A").Cells(i, 1) = value
value = value = Workbooks("FILE1.xls").Worksheets("sheet1")..Range("B:B").Cells(i, 1)
Wend
Repeat ste for "FILE2.xls" read data and write in "FILE3.xls"
and at the and you close
wb.SaveAs "c:\myfile\"FILE3.xls""
wb.Close
And close the read data file
Workbooks("FILE1.xls").Close
Workbooks("FILE2.xls").Close

Related

Running all files in a folder through a single workbook [duplicate]

This question already has an answer here:
Copying data from many workbooks to a summary workbook with Excel-VBA. Run time errors
(1 answer)
Closed 4 years ago.
Apologies if I over-word my dilemma. I want to make sure I'm crystal clear.
I have a workbook with a macro I wrote that analyzes and consolidates a large amount of data. The workbook itself has two worksheets: "Data Entry" and "Output". Data entry has the macro buttons within the first row, so the data starts at Cell "A2". Output is where the end data is placed, starting at Cell "A1".
What I would like to do is build upon the macro to be used in processing multiple files of raw data in a single process. Bear in mind none of the raw data files will be opened. Only the one running this macro. I would like to have the workbook itself:
Pull the worksheet data from all files in a folder, one at a time. There will be a variable amount of files in this folder. (To clarify, each raw data file placed into this folder will be a single worksheet with the data starting at Cell "A1", and the name of said files will vary)
Pull said data from a file and import it into "Data Entry" at Cell "A2"
Run my code, process the data and dump it into the worksheet "Output". (It's worth noting that "Data Entry" is 30 columns wide with variable row length, and output is variable in column and row length)
Take what is within the worksheet "Output", return it to the file it grabbed the raw data from, but in a new worksheet on the raw data workbook.
Loop this process until all raw data files have been run through the the workbook and have an "Output" worksheet.
The following will loop through a folder and add all filenames into an array if they have an .xlsm extension, this could be changed for whatever file you are looking for, then you can loop through the array to open each file and do whatever you need:
Sub LoopThroughDirectory()
Dim Arr() As String
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
FolderPath = "C:\Users\YOU\Documents"
Set objFolder = objFSO.GetFolder(FolderPath)
i = 0
For Each objSubFolder In objFolder.Files
'Debug.Print objSubFolder.Name
If Right(objSubFolder.Name, 4) = "xlsm" Then 'if file extension is = xlsm then add to array
ReDim Preserve Arr(i + 1)
Arr(i) = objSubFolder.Name
i = i + 1
End If
Next
For x = LBound(Arr) To UBound(Arr)
'Go through each file in your array
Next x
End Sub

Excel macro to open a folder of excel workbooks and copy 1 cell

I have a folder of .xlsx files, each identical in layout.
I need to write a macro in excel to open each file in turn (100+ files)
then get the data (a name) from a single cell, and drop it in a new excel worksheet, move on to the next and insert that below the last one etc.
Giving me basically a list of names from data not file names)
Here is (pretty much) exactly what you're trying to do. Next time do a little bit of googling before you ask! :)
http://www.excel-easy.com/vba/examples/files-in-a-directory.html
ROUGH CODE UNSURE IF IT WILL WORK: But here is the basic idea of what you need to modify in the example I sent you. If you look at the example again, it does everything you need and then some. Since you weren't interested in all worksheets, you don't have to loop through all worksheets in a workbook. You can just open it up, read your cell of interest, and then close it. The Do While loop will do this for every Excel file in your directory. AGAIN! Please modify this example accordingly before you use it.
Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer
Application.ScreenUpdating = False
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
i = i + 1
Workbooks.Open (directory & fileName)
Workbooks("files-in-a-directory.xls").Worksheets(1).Cells(i, 1).Value = Workbooks(fileName).Worksheets(1).Cells(x, y) <-- whatever your cell of interest is
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True

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 :-)

Loop through specific folder of csv, merging the 1st row of each into one workbook

I've looked through several posts and can't seem to find a suitable answer - similar, but not quite what I'm looking for.
I would like some code that loops through a series of csv-files (~ 200 at a time) within a specific folder. It needs to import/copy the values of the first row of each of these csv-files to one (main) workbook. These csv-file-names are numerical (eg 20140213075458) any files that does not meet this criteria (14 characters, numbers only AND FileFormat = csv) should not be considered.
Any guidance will be much appreciated!
Add the Microsoft Scripting Runtime library to your project and use Use FileSystemObject class to loop through all files. You can use the Like operator to check if file name matches your criteria.
i think this add-in might help you for sure.
RDBMerge used to Merge Data from Multiple Excel Workbooks,
csv and xml files into a Summary Workbook.
I am just going to outline the operations you need to do. You can work from that.
Get the filename of each file in each folder: fname = Dir(Your_Folder_Path)
Initialize file read counter: i=1
Loop through all files in folder:
Do While fname <> "" 'Loop all files in folder
Check your conditions:
Extension = Split(fname, ".")(Ubound(Split(fname, "."))) 'Extract extension of file
Name = Split(fname, ".")(Ubound(Split(fname, "."))-1) 'Extract name of file without extension
If Extension = "csv" And Len(Name) = 14 And IsNumeric(Name) Then 'Check csv, length of name 14 and numeric name
Open csv, read first line and close it:
Open Your_Folder_Path & fname For Input As #f1
Line Input #f1, csvFirstLine
Close #f1
Put data in workbook:
ActiveSheet.Range("A" & i).Value = csvFirstLine 'Put line in corresponding row
ActiveSheet.Range("A" & i).TextToColumns Comma:=True 'Separate data by comma
i=i+1 'File counter +1
Exit ifs and close loops: End If Loop

Extracting certain cells from excel files in a specified directory

I am a VBA novice and I am trying to write a code that will copy the following data from multiple csv files all stored in the same directory.
I need it to open each csv file
Check IF Row 8 in columns H through CA for any cells that have the value ="TotalLMP" (Sample: Cell H8="TotalLMP")
THEN copy the value from both Row 7 and Row 19 of any columns that have that value ="TotalLMP" in Row 8 in two new columns (Sample: SINCE H8="TotalLMP", COPY H7="100" AS COLUMN A, COPY H19 = "26.437" AS COLUMN B)
THEN copy the value from cell $A$9 in a third column (Sample: COPY A9="20100101" AS COLUMN C")
after finishing loop through each csv file close and go to next
Then in the new active worksheet in the blank excel file would store each value as follows:
.......A .............. B ................ C
1 .. 100 .... 26.437 .... 20100101
2 .. 200 .... 26.585 .... 20100101
Let me help you with the CSV looping for now since this is rather hard for a beginner. I'm sure you will figure out how to test for a value in row 8. If not, you can always ask for more help!
In order to do so, you will have to use the Microsoft Scripting Runtime.
I suggest placing all of the csv file you want to open in the same directory, and only those to avoid potential problems.
Open a new workbook and go to the VBE (ALT + F11). Create a new module. Click in this new module, then go to Tools > References> Microsoft Scripting Runtime. This will let it know it will have to use that module and its objects.
Save the workbook as an macro-enabled workbook (.xls or .xslm for newer versions) in the same directory as your CSV (or somewhere else...)
Then start coding:
Sub Import_all_Csv()
' Reference Needed: Microsoft Scripting Runtime
' Dim some pointers to know what objects you will be manipulating thereafter
Dim MyWs, CSV As Worksheet
Set MyWs = ActiveSheet ' Meaning you will have to run the macro from the spreadsheet you want to export to. Feel free to replace that
Dim wbCSV As Workbook
' Those are the objects that belong to the reference Microsoft Scripting Runtime
Dim oFSO As FileSystemObject
Dim oFld As Folder
Dim oFile As File
Dim File As String
' Initialize the FileSystemObject
Set oFSO = New FileSystemObject
' That will only work on windows so I'm adding an error handler to ignore it if need be
On Error Resume Next
ChDir ThisWorkbook.Path
On Error GoTo 0 ' I'm asking VBA to throw an error now
' Dialog box to select the first csv file (this will let you choose another directory everytime)
File = Application.GetOpenFilename("Comma Separated Values File (*.csv*), *.csv*")
If File = "False" Then
Exit Sub ' Quit the macro if user canceled
Else
' Else get the path of the parent folder of that file
Set oFld = oFSO.GetFolder(oFSO.GetParentFolderName(File))
End If
' Go through each file in that folder
For Each oFile In oFld.Files
' Only open the CSV files
If oFile.Type = "Microsoft Excel Comma Separated Values File" Then
' Open it and set the first sheet (There is only one anyway)
Set wbCSV = Workbooks.Open(oFile)
Set CSV = wbCSV.Sheets(1)
' ============================
' Do what you want to do Here
' THIS IS A PLACEHOLDER
' Example to copy value of H8 in the CSV file to A2 the destination worksheet so you can see how to point to the correct cells in both files
MyWs.cells(1,2).value = wCSV.cells(8,8).value
' End of what you want to do
' ============================
' Close the CSV file without savings changes before going through the next one
wbCSV.Close False
End If
Next oFile
End Sub
I hope this helps! Good luck learning more VBA!
Best,
Julien