Newbie here.
So I have a dozen of these TXT/DTA files that look something like this and I want to stack them side by side. I want each file appended to the right, merged into one big file
Not knowing much about VBA I looked around and merged a few codes that seems to do it for xlsx files but doesn't for DTA files which is what I have. The code asks for a folder and loops through the files one by one.
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
'---Open the first file only
Workbooks.Open (MyFile)
Workbooks(MyFile).Worksheets("Sheet1").Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Workbooks("CV Combined.xlsm").Worksheets("Sheet1").Range("A1")
Workbooks(MyFile).Close SaveChanges:=False
MyFile = Dir
Do While MyFile <> ""
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(fileName:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Workbooks.Open (MyFile)
Workbooks(MyFile).Worksheets("Sheet1").Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Workbooks("CV Combined.xlsm").Worksheets("Sheet1").Range("A1").End(xlToRight).Offset(0, 1)
Workbooks(MyFile).Close SaveChanges:=False
wbk.Close SaveChanges:=True
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
Any help would be appreciated.
MyFile = Dir(MyFolder) returns only the filename in MyFile so to open the first file use Workbooks.Open (MyFolder & MyFile). When the text file is opened the sheet name is the filename so Workbooks(MyFile).Worksheets("Sheet1") needs to be Workbooks(MyFile).sheets(1). Because your text file only has data in column A on row 1 Selection.End(xlToRight) will go the last column on the sheet XFD1 and then Selection.End(xlDown) will go to the last row XFD1048576.
Option Explicit
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbDTA As Workbook 'Used to loop through each workbook
Dim ws As Worksheet, wsDTA As Worksheet, rng As Range
Dim iCol As Long, n As Long
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
Set ws = Workbooks("CV Combined.xlsm").Sheets(1)
iCol = 1
'Loop through all files in a folder until DIR cannot find anymore
Application.ScreenUpdating = False
MyFile = Dir(MyFolder)
Do While MyFile <> ""
Set wbDTA = Workbooks.Open(MyFolder & MyFile, False, False)
Set wsDTA = wbDTA.Sheets(1)
Set rng = wsDTA.UsedRange
rng.Copy ws.Cells(1, iCol)
iCol = iCol + rng.Columns.Count + 1 ' add blank column
n = n + 1
wbDTA.Close SaveChanges:=False
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
MsgBox n & " files imported from " & MyFolder, vbInformation
End Sub
Related
Problem:
A problem in making a cell reference in VBA for source workbook name. Error 9 subscripts out of range.
Task I am doing?
Ex. I have to copy 32 columns out of 50 columns from a workbook(Master) into a new workbook. I am able to make a code to copy and paste the column in the required sequence in new workbook.
The master workbook is a template of a register to take peoples information and it saved with a new name.
I have more than 65 workbooks(Master) to copy. I was trying to make a cell reference where I paste the source workbook(Master) name. I am aware that source workbook has to be open will running VBA.
I made icell as variable to fetch that value from cell B2, where I pasted workbook name but code is not running.
Code attached
Any suggestion is highly appreciated.
Sub Copy_Paste()
Dim iCell As String
iCell = Workbooks("Crack it").Worksheets("Intro").Range("B2").Value
'B2 will store the name of source workbook for copying data which will keep on changing
Workbooks("iCell").Worksheets("Register").Range("E2:E50").Copy
Workbooks("Crack it.xlsm").Worksheets("Risk").Range("A2").PasteSpecial Paste:=xlPasteValues 'Refid
Workbooks("iCell").Worksheets("Register").Range("H2:H50").Copy
Workbooks("Crack it.xlsm").Worksheets("Risk").Range("B2").PasteSpecial Paste:=xlPasteValues 'Tags
Workbooks("iCell").Worksheets("Register").Range("A2:A50").Copy
Workbooks("Crack it.xlsm").Worksheets("Risk").Range("c2").PasteSpecial Paste:=xlPasteValues 'Name
Workbooks("iCell").Worksheets("Register").Range("Z2:Z50").Copy
Workbooks("Crack it.xlsm").Worksheets("Risk").Range("D2").PasteSpecial Paste:=xlPasteValues 'Element
...... code keeps on repeating till column 32th
End Sub
I ahve somethign similar, I read all the files located on a folder for your case you will save all the 65 Workbooks in a folder, then read each one of them with a loop, once it takes the first book opened you will take the info:
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1) & sItem + "\"
FilePathBox.Value = sItem
End With
NextCode:
GetFolder = sItem & "\"
Set fldr = Nothing
If you see my code above it taks the url of the folder, then I will start a process that will see file by file:
Private Sub UserForm_Activate()
UserForm1.Top = (Application.Height / 2) - (UserForm1.Height / 2) + 45
UserForm1.Left = (Application.Width / 2) - (UserForm1.Width / 2) + 200
UserForm1.Label1.Visible = True
Label1.Caption = ""
'-----------------------------------------THIS IS THE LOOP OFR EACH FILE INTO THE FOLDER--------------------------------------------------
MyPath = UserForm2.FilePathBox.Value
Dim strFilename As String
strFilename = Dir(MyPath & "*.txt", vbNormal)
filesc = 1
If Len(strFilename) = 0 Then Exit Sub
Do Until strFilename = ""
Application.DisplayAlerts = False
If filesc >= 1 Then
showBarName.Caption = showBarName.Caption & strFilename
'Worksheets.Add(Worksheets(Worksheets.Count)).Name = "Data"
Call ThisWorkbook.XY_Data((UserForm2.FilePathBox.Value & strFilename), (strFilename & ""))
showBarName.Caption = "Generating XY Data for %PATH%/"
End If
filesc = filesc + 1
counter = counter + cols
strFilename = Dir()
Loop
'------------------------------------------END--------------------------------------------------------------------------------------------
Worksheets("Spec").Visible = True
For Each ws In ThisWorkbook.Worksheets
If ws.Name = "Spec" Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
UserForm1.Hide
showBarName.Caption = "Saving File"
'THIS IS FOR XLSX
Application.StatusBar = "Save your file into the PNL Project path."
Application.DisplayAlerts = False
Dim hoja As Worksheet
For Each hoja In Sheets
If ActiveSheet.Name = "Data" Then
ActiveWindow.SelectedSheets.Delete
End If
Next hoja
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Excel Workbooks (*.xlsx), *.xlsx")
If fileSaveName <> False Then
Application.ActiveWorkbook.SaveAs Filename:=fileSaveName, FileFormat:=51
End If
showBarName.Caption = "Generating XY Data for %PATH%/"
'This is to close the macro without saving
Application.StatusBar = "XY Data Generated by Yazaki <<erik.floresdelfin#mx.yazaki.com>>"
'ThisWorkbook.Close savechanges = False
Application.DisplayAlerts = True
End Sub
Then on the above code in some part I take each file in txt format, and I call a method which contains the url of the file that I want to open, the rest should be taking what tou need to copy and paste on the actual file, the final code I show is how to save the file asking to the user, sorry for the trash code but I think you caould manage taking what you need.
I am trying to set up a macro where you can open certain files with a certain name without having to go through the files I have already filtered through.
In the code before this macro, it loops through an entire folder, and opens all of the files that meet a criteria, pull a number from there, pastes into the new workbook, closes that workbook, and goes to the next file.
I have the criteria in a range in the current workbook, and I want to use that criteria when determining which workbooks to open in the folder.
I'm wondering if there is a way to start looping through the folder starting with the last file that was opened using the macro before.
EDIT: The following code is what I have so far.
Sub LoopThroughFilesInFolder()
'=============================================================================
'Looping through all of the files in the folder, and grabbing the last value
'=============================================================================
Dim wb As Workbook
Dim MyPath As String
Dim MyFile As String
Dim myExtension As String
Dim FolderPicker As FileDialog
Application.ScreenUpdating = False
'Retrieve Target Folder Path From User
Set FolderPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FolderPicker
.Title = "Select a Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
'In case of cancel
NextCode:
MyPath = MyPath
If MyPath = "" Then GoTo ResetSettings
'Target File Extension
myExtension = "*1*9 Restraint*.xls*"
'Target Path with Ending Extension
MyFile = Dir(MyPath & myExtension)
'Loop through each Excel file in folder
LastRow = Sheets("Sheet Name").Cells(Rows.Count, 1).End(xlUp).Row
i = LastRow - 1
Do While MyFile <> ""
If MyFile Like Cells(LastRow, 1).Value Then
Set wb = Workbooks.Open(Filename:=MyPath & MyFile, ReadOnly:=True)
'Ensure Workbook has opened before moving on
DoEvents
'Find last row
LastRow = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
'Grab value next to last row
LastValue = ActiveSheet.Cells(LastRow, 2).Value
If WorksheetFunction.IsNumber(LastValue) = False Then
LastValue = ActiveSheet.Cells(LastRow, 3).Value
End If
'Go back to graph workbook
Workbooks("Workbook Name").Sheets("Sheet Name").Cells(i, 2).Value = MyFile
Workbooks("Workbook Name").Sheets("Sheet Name").Cells(i, 3).Value = LastValue
i = i + 1
wb.Close savechanges:=False
DoEvents
MyFile = Dir
End If
Loop
'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This is looping through the entire folder (there are about 1000 files). My question above assumes that we have already done this macro, and the macro I am trying to currently write will only open the most recent files matching a certain criteria, still from the same folder though (but without having to loop through the files that were already opened from the previous macro).
Dir$() without a new file pattern retrieves the next matching file (Win32 FindNextFile), whereas Dir$(file pattern) starts the search over again, even if the pattern is the same as the previous one (Win32 FindFirstFile).
That being said, maybe do something like
Static bolBeenHere As Boolean
If bolBeenHere = False Then
' First search, use the file search pattern
' Target Path with Ending Extension
MyFile = Dir(MyPath & myExtension)
bolBeenHere = True
Else
' Retrieve the next matching file
MyFile = Dir$()
End If
' Stuff
Do While MyFile <> ""
...
Loop
A small performance advice. Use
Do While Len(MyFile) > 0
instead of
Do While MyFile <> ""
A string comparison "costs" more than a numeric comparison.
I need to open and copy the information from several workbooks and from the same cells of the same sheet name, to one summary sheet. I am using the following VBA code that is working but it paste everything in the same raw (resulting in having the information in only one raw from last workbook opened). I need the Macro to paste each time it start a loop on the following raw. How can I do this?
Here's the code I have so far:
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> “”
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(Filename:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Range("B3").Select
Selection.Copy
Windows("Forecast.xlsm").Activate
Cells(3, 1).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
wbk.Activate
Range("C11:J11").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Forecast.xlsm").Activate
Cells(3, 4).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
wbk.Close savechanges:=False
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
From what I understand, you just want to copy values from some ranges in different files to subsequent rows in another file.
To copy a range of cells in VBA you don't have to select them. It is better to use Range.Copy method.
In your case you probably want to do something like:
wbk.Worksheets(1).Range("C11:J11").Copy _
destination:=ThisWorkbook.Worksheets(1).Range("D4")
By the way: Cells(3, 1).Offset(1, 0) is the same as: Cells(4,1).
To paste each time to the next row you can just count them. Outside of the while loop declare a variable. For example: Dim i as Integer. Then in each iteration increment it: i = i + 1. Then you can copy like this:
wbk.Worksheets(1).Range("C11:J11").Copy _
destination:=ThisWorkbook.Worksheets(1).Range( Chr(Asc("D")+i) & ":4")
Sub Forecast()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
Dim i As Integer
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> “”
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(Filename:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
wbk.Worksheets("Dashboard ctc").Range("B3").Copy
Workbooks("Forecast.xlsm").Worksheets(1).Range("A" & Chr(Asc("3") + i)).PasteSpecial Paste:=xlPasteValues
wbk.Worksheets("Dashboard ctc").Range("B11:J11").Copy
Workbooks("Forecast.xlsm").Worksheets(1).Range("D" & Chr(Asc("3") + i)).PasteSpecial Paste:=xlPasteValues
i = i + 1
wbk.Close savechanges:=False
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
I am trying to copy a sheet from one file and then paste it to an established tab in about 6 files in an established folder. I have this code, but it only works for the first file in the folder. It is also creating a blank workbook for some reason. Any suggestions?
Sub LoopThroughFiles()
Dim wbk As Workbook
Dim Filename As String
Dim FirstFile As String
Dim FileDirectory As String
Dim x As Workbook
Set x = Workbooks.Open("test.xlsx")
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 0 Then
MsgBox "You did not select a folder"
Exit Sub
Else
FileDirectory = .SelectedItems(1) & "\"
End If
End With
Set wbk = Workbooks.Add
Filename = Dir(FileDirectory)
FirstFile = Filename
Do Until Filename = ""
Dim new_wb As Workbook
Set new_wb = Workbooks.Open(FileDirectory & Filename)
If FirstFile = Filename Then
x.Sheets("report").UsedRange.Copy
new_wb.Sheets("roster").Range("a1").PasteSpecial
End If
new_wb.Close savechanges:=True
Filename = Dir
Loop
MsgBox "All store totals have been added"
End Sub
Sub LoopThroughFiles_Paste_Roster()
Dim wbk As Workbook 'New workbook the data is added to
Dim Filename As String
Dim FirstFile As String
Dim FileDirectory As String
Dim x As Workbook
Dim y As Workbook
Set x = Workbooks.Open("Copy Doc 1")
Set y = Workbooks.Open("Copy Doc 2")
'display the folder picker dialog box so user can select a folder
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 0 Then
MsgBox "You did not select a folder"
Exit Sub
Else
FileDirectory = .SelectedItems(1) & "\"
End If
End With
'retrieve the name of the first file in the folder using Dir
Filename = Dir(FileDirectory)
FirstFile = Filename
'Loop through all the files in the folder
'open the file
Do Until Filename = ""
Set wbk = Workbooks.Open(FileDirectory & Filename, UpdateLinks:=False, Password:="Password123")
With wbk
x.Sheets("report").UsedRange.Copy
wbk.Sheets("roster").Range("a1").PasteSpecial
y.Sheets("Setup").UsedRange.Copy
wbk.Sheets("PTO Taken and Req").Range("a1").PasteSpecial
End With
'save and close the file
'get the next file in the folder
wbk.Close savechanges:=True
Filename = Dir
Loop
MsgBox "All pages have been updated"
End Sub
Edit: After user3561813 the suggestion of adding "/", it now read the first file. I have an out of range error message "9". It does read the first file correctly. Ultimately I am trying to open each file, and read the name and age (this is a testing not the real production form). And retrieve the values back to my main worksheet.
Original question
I am trying to read hundred of excel forms in a folder, read a particular cell position, and record them into my testing worksheet. I googled this tutorial and tried to write my code. But when I execute the Getting Folder function, selected a folder path, it does not loop the excel files I have. (or record their names)
'Source: https://www.youtube.com/watch?v=7x1T4s8DVc0
Sub GettingFolder()
Dim SelectedFolder As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select folder"
.ButtonName = "Confirm"
.InitialFileName = "U:\"
If .Show = -1 Then
'ok clicked
SelectedFolder = .SelectedItems(1)
MsgBox SelectedFolder
' This is where I want to call my function
LoopFiles (SelectedFolder)
Else
'cancel clicked
End If
End With
End Sub
' Source: http://www.excel-easy.com/vba/examples/files-in-a-directory.html
Sub LoopFiles(path As String)
Dim directory As String, fileName As String, sheet As Worksheet
Dim i As Integer, j As Integer
' Avoid Screen flicker and improve performance
Application.ScreenUpdating = False
' Fixed per suggestion below..
directory = path & "\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
i = i + 1
j = 2
Cells(i, 1) = fileName
Workbooks.Open (directory & fileName)
For Each sheet In Workbooks(fileName).Worksheets
Workbooks("Testing.xlsm").Worksheets(1).Cells(i, j).Value = sheet.Name
j = j + 1
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
' Reset the screen update setting
Application.ScreenUpdating = True
End Sub
Interesting question! This should do it for you. Modify as needed.
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsx"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
Row = 1
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Change First Worksheet's Background Fill Blue
ThisWorkbook.Worksheets("Sheet1").Range("A" & Row).Value = Worksheets(1).Range("A1").Value
Row = Row + 1
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
In your code, the path variable may not contain a trailing backslash. This causes the following code in your LoopFiles(<>) SubRoutine to be inaccurate:
directory = path
fileName = Dir(directory & "*.xl??")
Filename would look something like: c:\users\name\documentshello.xlsx
Try changing the above code to:
directory = path & "\"
fileName = Dir(directory & "*.xl??")
Does that fix the problem?