I have a macro excel file that does some clean up on cells and I need to import a single sheet from various files on the same folder. For example I need the sheet1 from all the excel files located on the same folder as my macro file. I have a code to do that manually but I need to be able to do it automatically either by selecting the files or running another macro to select them no matter the amount of files on the folder.
Sub Carga_Masiva()
Dim fName As String, wb As Workbook
fName = Application.GetOpenFilename("Excel Files (*.xl*), *.xl*")
Set wb = Workbooks.Open(fName)
For Each sh In wb.Sheets
If Application.CountA(sh.Cells) > 0 Then
sh.Copy Before:=ThisWorkbook.Sheets(1)
Exit For
End If
Next
wb.Close False
End Sub
I'd prompt user for a folder and then iterate over each file except the one with your macro.
To prompt for a folder use this solution (in my code as optional variant): link
Complete code below:
Sub Carga_Masiva()
Dim sh As Worksheet
Dim fName As String, wb As Workbook
fName = Application.GetOpenfnamename("Excel fnames (*.xl*), *.xl*")
Set wb = Workbooks.Open(fName)
For Each sh In wb.Sheets
If Application.CountA(sh.Cells) > 0 Then
sh.Copy Before:=ThisWorkbook.Sheets(1)
Exit For
End If
Next
wb.Close False
End Sub
Sub CopyToThisWorkbook()
Dim wbMacro, wb As Workbook
Set wbMacro = ThisWorkbook
Dim sh As Worksheet
Dim folderPath, fName, tabName As String
folderPath = wbMacro.Path & Application.PathSeparator
'Prompt variant
'folderPath = GetFolder & Application.PathSeparator
fName = Dir(PathName:=folderPath)
Do
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Open all files except the one with macro
If fName <> wbMacro.Name Then
'Your code
Set wb = Workbooks.Open(wbMacro.Path & "\" & fName)
For Each sh In wb.Sheets
If Application.CountA(sh.Cells) > 0 Then
tabName = sh.Name & "_" & Right(wb.Name, 10) 'Optional - rename Worksheet to be copied
sh.Name = tabName 'Optional
sh.Copy Before:=wbMacro.Sheets(1)
Exit For
End If
Next sh
wb.Close SaveChanges:=False
End If
fName = Dir
Loop Until fName = ""
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Function GetFolder() As String 'Optional variant
Dim fldr As fnameDialog
Dim sItem As String
Set fldr = Application.fnameDialog(msofnameDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialfnameName = Application.DefaultfnamePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Related
I would like to
Loop through all excel files in a folder "\xxxx\INPUT\File1.xlsm".
Copy a particular sheet "Template".
Paste the "Template" sheet into another file "\xxxx\TEMPLATE\WEBADI.xlsm".
Rename file WEBADI.xlsm as File1_WEBADI and save it in folder "\xxxx\OUTPUT\File1_WEBADI.xlsm
Below is the VBA code I worked on.
It executes fine until the step where it copies the sheet "Template" to the WEBADI.xlsm
Once the sheet is copied the VBA code exits execution without any error.
Sub CpyRebateADI()
Dim myPath As String
Dim OutputPath As String
Dim myExtension As String
Dim myFile As String
Dim wb As Workbook
Dim ws As Worksheet
Dim wb1 As Workbook, Wb2 As Workbook, wb3 As Workbook
Set wb1 = ActiveWorkbook
myPath = "\\XXXX\INPUT\"
OutputPath = "\\XXXX\OUTPUT\"
If Right(myPath, 1) <> "\" Then
myPath = myPath & "\"
End If
On Error GoTo ErrHandler
previousSecurity = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
myExtension = "*.xl*"
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
Application.DisplayAlerts = False
Debug.Print (myFile)
filestr1 = "\\XXXX\TEMPLATE\WEBADI.xlsm"
Set wb3 = Workbooks.Open(filestr1, UpdateLinks:=False)
Set Wb2 = Workbooks.Open(filename:=myPath & myFile, UpdateLinks:=False)
Dim source_worksheet As Worksheet
Set source_worksheet = Wb2.Worksheets("Template")
source_worksheet.Visible = True
Dim target_worksheet As Worksheet
Set target_worksheet = wb3.Worksheets("WebADI")
source_worksheet.Copy After:=target_worksheet
'This is where the macro stops executing
wb3.SaveAs filename:=OutputPath & myFile & "_WebADI", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Wb2.Close SaveChanges:=False
myFile = Dir
Loop
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.AutomationSecurity = previousSecurity
ErrHandler:
MsgBox Err.Description, vbExclamation
End Sub
I have a problem with a macro, I have a sample file with a button that I would like to use to run two files in the background. One wb = this is a template and wbMe pli with data that I would like to copy to wbMe. However, when I run the code, I get subcprite out of range. Where I have an error, such a sheet exists + there is data there in the cell
Sub COREP_ITS()
Dim strPath As String
Set wb = ThisWorkbook
Set wbMe = ThisWorkbook
strPath = selectFile
If strPath = "" Then Exit Sub
Set wbMe = ThisWorkbook
MyFolder = "sample_folder"
MyFile = Dir(MyFolder & "\CMR - CJ_MINIMAL*.xlsx")
If MyFile <> "" Then
Set wb = Workbooks.Open(MyFolder & "\" & MyFile, UpdateLinks:=0)
Else
Exit Sub
End If
''C_0700_002''
wbMe.Sheets("Tabela_COREP").Range("F14").Copy
wb.Sheets("C_0700_0002").Range("G14").PasteSpecial Paste:=xlPasteValues
End Sub
Private Function selectFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = ActiveWorkbook.Path
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel", "*.xlsx"
If .Show = True Then selectFile = .SelectedItems(1)
End With
End Function
You don't open the user-selected file.
You need to pass strPath to Workbooks.Open
strPath = selectFile
If strPath = "" Then Exit Sub
Set wbMe = Workbooks.Open(strPath)
I am writing a function that iterates through files in a folder. In each file, iterate through the sheets and save them as CSV files. I tested them without going through the sheets and it works fine. However, when I loop through the sheets, it keeps looping through the files. I ran the debug and found that when it is at the end of the last file, it goes back to the first file. I cannot find what was wrong. Here is my code:
Sub morningstar_VBA()
'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 filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
'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)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
For w = 1 To Worksheets.Count
With Worksheets(w).Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
filename = .Worksheets(1).Name
path_to_save = "E:\Morningstar_download\test\" & filename
.SaveAs filename:=path_to_save, FileFormat:=xlCSV
DoEvents
.Close savechanges:=False
End With
End With
Next w
wb.Close savechanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'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
Maybe try this out :
Sub morningstar_VBA()
'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 filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
'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)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(filename:=myPath & myFile)
Windows(wb.Name).Visible = False
'Ensure Workbook has opened before moving on to next line of code
For w = 1 To wb.Worksheets.Count
With wb.Worksheets(w).Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
filename = ActiveWorkbook.Worksheets(1).Name
path_to_save = "E:\Morningstar_download\test\" & filename
wb.SaveAs Filename:="E:\Morningstar_download\test\" & filename & ".csv", FileFormat:=xlCSVWindows
Workbooks( Worksheets(w).Name & ".XLS").Close
End With
Next w
wb.Close savechanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'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
i would split this into two parts; mainly because it is easier to handle the code, but also in case you need parts of the code in other circumstances. The sub "Dateien_auswaehlen" can be used to do anything with the choosen files, just by choosing some other routine then morningstar:
Sub Dateien_auswaehlen()
Dim FldrPicker As FileDialog
Dim fso As Object
Dim objFld As Object
Dim objFiles As Object
Dim file
Dim myPath As String
'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)
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFld = fso.GetFolder(myPath)
Set objFiles = objFld.Files
For Each file In objFiles
'here any sub can be called for working with the files found:
If LCase(file.Name) Like myExtension Then Call morningstar_VBA(myPath, file.Name)
Next
'Message Box when tasks are completed
MsgBox "Task Complete!"
Set fso = Nothing
Set objFld = Nothing
Set objFiles = Nothing
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Sub morningstar_VBA(path As String, filename As String)
Dim wb As Workbook
Dim myFile As String
Dim myExtension As String
Dim path_to_save As String
Dim w As Long
Set wb = Workbooks.Open(path & filename)
'Ensure Workbook has opened before moving on to next line of code
For w = 1 To Worksheets.Count
With Worksheets(w).Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
filename = .Worksheets(1).Name
path_to_save = "E:\Morningstar_download\test\" & filename
.SaveAs filename:=path_to_save, FileFormat:=xlCSV
DoEvents
.Close savechanges:=False
End With
End With
Next w
wb.Close savechanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
End Sub
Hi i have this code that counts the number of time "T" appears in the various workbooks where each workbook have around 10-12 sheets. the main objective is to have the final workbook get the the total number of times T appeared as it loops through the file.
Private Sub CommandButton3_Click()
Dim ws As Worksheet
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim x As Integer
Dim wash_count As Integer
'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 = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
For Each ws In wb.Sheets
If ws.Name <> "Summary" Then
For x = 5 To 74
If StrConv(ws.Cells(x, 2).Value, vbProperCase) = "Wash" And StrConv(ws.Cells(x, 4).Value, vbProperCase) = "T" Then 'added the StrConv to make sure you don't loose a case just because it was written in capital or lowercase letters
wash_count = wash_count + 1
End If
Next x
End If
Next ws
Sheets("Summary").Range("D6") = wash_count
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'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
The problem now is that the previous workbooks with the sheets also named "Summary" gets the counter input inside it too.
right now the code gets the final count in the last workbook, but how do i avoid having it appear in the summary pages in the previous workbooks, i want to direct all the counts only to the final workbook.
Thanks in advance
You can do something like this:
Dim ColFiles As New Collection, i As Long
'...
'...
'...
'collect the files first
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
ColFiles.Add myPath & myFile
myFile = Dir()
Loop
'now loop over the collection
For i = 1 To ColFiles.Count
Set wb = Workbooks.Open(ColFiles(i))
'count things in wb
'is this the last file?
If i = ColFiles.Count Then
wb.Sheets("Summary").Range("D6") = wash_count
wb.Close True 'save
Else
wb.Close False 'no save
End If
Next i
I have written the following code in VBA. When debugging, I am not able to find any problems. It is not creating nor converting any file into .CSV.
Sub SaveToCSVs()
Dim fDir As String
Dim Wb As Workbook
Dim wS As Worksheet
Dim csvWs As String, csvWb As String
Dim extFlag As Long '0 = .xls & 1 = .xlsx extension types
Dim fPath As String
Dim sPath As String, dd() As String
fPath = "C:\Users\DA00358662\Documents\XLSCONV\*.*"
sPath = "C:\Users\DA00358662\Documents\XLSCONV\"
fDir = Dir(fPath)
extFlag = 2
Do While (fDir <> "")
If Right(fDir, 4) = ".xls" Or Right(fDir, 5) = ".xlsx" Then
extFlag = 0
Else
extFlag = 2
End If
On Error Resume Next
If extFlag = 0 Then
fDir = Dir
Set Wb = Workbooks.Open(fPath & fDir)
csvWb = Wb.Name
dd = Split(csvWb, ".")
For Each wS In Wb.Sheets
wS.SaveAs dd(0) & wS.Name & ".csv", xlCSV
Next wS
Wb.Close False
Set Wb = Nothing
fDir = Dir
On Error GoTo 0
End If
Loop
End Sub
with this code (standard for my use) you can find that you need (modify as your need).
In short the code ask which directory to loop and for each file, with the corresponding extension, in this directory it open file, save as csv in the some directory, and close the original file.
Sub SaveAsCsv()
Dim wb As Workbook
Dim sh As Worksheet
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 Exit Sub
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
nameWb = myPath & Left(myFile, InStr(1, myFile, ".") - 1) & ".csv"
ActiveWorkbook.SaveAs Filename:=nameWb, FileFormat:=xlCSV
ActiveWorkbook.Close savechanges:=False
'Get next file name
myFile = Dir
Loop
'Reset Macro Optimization Settings
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
The Moment you concatenate fPath and fDir to open your Workbook, you get something like:
"C:\Users\DA00358662\Documents\XLSCONV\*.*MyWorkbook.xls"
Note *.* in the middle ruining your day. I think you want to use sPath here?