I have multiple (5 to be exact) .csv's in a folder, and I would like to make a macro that lets me select the csv files in a folder and import them to a macro enabled blank file. Here is a step by step for what I want to do:
Open the main.xlsm
Press a macro button in the toolbar that says "Import the CSV's"
This will automatically open a browser window and let you find the CSV's somewhere
Press Ok and BOOM! just like that all your csv's are exported as xlsm and are separate sheets in the current blank sheet
I tried many different methods of doing this, but I don't think I am on the right path. here is one:
Sub convert_to_macro()
'This first line is crap though. It only lets you export it to a certain place
ChDir "C:\Users\pal\Documents\CMSe\Lucys Computer"
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
Exit Sub
End If
something = .SelectedItems(1)
End With
ActiveWorkbook.SaveAs Filename:= _
"something.xltm", _
FileFormat:=xlOpenXMLTemplateMacroEnabled, Password:="", WriteResPassword _
:="", ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
Thanks for any help given
Something like this which adds all the csvs to a single file.
Sub convert_to_macro()
Dim Wb As Workbook
Dim Wb1 As Workbook
Dim fd As FileDialog
Dim strWB
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
'set initial directory to search
.InitialFileName = "c:\temp"
.Filters.Clear
.Filters.Add "csv files", "*.csv"
.Show
If .SelectedItems.Count = 0 Then
MsgBox "No selection, exiting"
Exit Sub
End If
End With
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set Wb = Workbooks.Add(1)
For Each strWB In fd.SelectedItems
Set Wb1 = Workbooks.Open(strWB)
Wb1.Sheets(1).Copy after:=Wb.Sheets(Wb.Sheets.Count)
Wb1.Close False
Next
Wb.Sheets(1).Delete
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
End Sub
Related
I need to run Excel VBA code that will open 50 .xlsx files in a single folder, one by one I suppose, protect the sheet, save and close.
I would love a dialog that tells me how many files were found to first confirm the number of files in the folder.
Here's the code that has been suggested to open, protect, save and close a single file.
Sub Macro1()
'
' Macro1 Macro
'
'
ChDir "G:\Folder\Subfolder\Projects"
Workbooks.Open Filename:= _
"G:\Folder\Subfolder\Projects\Filename.xlsx"
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowFormattingCells:=True
ActiveWorkbook.Save
ActiveWindow.Close
End Sub
This should do the trick.
Sub protect_excel_files_sheets_in_folder()
Dim wb As Workbook
Dim sheet As Worksheet
Dim file_path As String, work_file As String, file_types As String
Dim work_folder As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.ButtonName = "Select"
.Show
If .SelectedItems.Count <> 1 Then
GoTo CleanExit
End If
work_folder = .SelectedItems(1) & "\"
End With
file_types = "*.xls*"
work_file = Dir(work_folder & file_types)
Do While work_file <> ""
Set wb = Workbooks.Open(Filename:=work_folder & work_file)
For Each sheet In wb.Sheets
sheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowFormattingCells:=True
Next
Sheets(0).Activate
wb.Close SaveChanges:=True
work_file = Dir
Loop
CleanExit:
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I just happen to have something similar, to password protect and unprotect all file and sheets, in my library. I took out the password part and it should work for you.
I am looking to import the first sheet of all files in a folder that I select and rename to their original file name except for one. If the file Forecast Report exists in the files, I want to copy the second sheet.
I have tried a code that imports all sheets from all files but this is excessive because I then must go in and delete many extra sheets. The code I have below works great for importing my files. I am looking for a way to add to this "if Forecast Report exists, copy the 2nd sheet."
Sub My Data()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim s As String
Application.ScreenUpdating = 0
With Application.FileDialog(msoFileDialogOpen)
.Title = "Select all reports:"
.Filters.Clear
.Filters.Add "All Excel Files", "*.xl*"
.AllowMultiSelect = True
.Show
If .SelectedItems.Count > 0 Then
For i = 1 To .SelectedItems.Count
Workbooks.Open.SelectedItems (i)
Workbooks.Open .SelectedItems(i)
With ActiveWorkbook
s = .Name
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Split(s, ".")(0)
.Close 0
End With
Next
End If
End With
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Use an IF statement to test if ActiveWorkbook.name is "Forecast Report.xlsx" (change the extension as needed). If found copy .Sheets(2), etc. If not found then copy .Sheets(1)
With ActiveWorkbook
s = .Name
If s = "Forecast Report.xlsx" Then
.Sheets(2).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Split(s, ".")(0)
Else
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Split(s, ".")(0)
End If
End With
I have the following code that will open/save/close any/all workbooks in a folder. It works great, however, I also need it to include sub folders. The code needs to work without restrictions on the number of folders, sub folders and files, if possible.
I'm working with Excel 2010 and I'm new to VBA - would really appreciate any help!
Sub File_Loop_Example()
'Excel VBA code to loop through files in a folder with Excel VBA
Dim MyFolder As String, MyFile As String
'Opens a file dialog box for user to select a folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
'stops screen updating, calculations, events, and statsu bar updates to help code run faster
'you'll be opening and closing many files so this will prevent your screen from displaying that
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'This section will loop through and open each file in the folder you selected
'and then close that file before opening the next file
MyFile = Dir(MyFolder & "\", vbReadOnly)
Do While MyFile <> ""
DoEvents
On Error GoTo 0
Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
ActiveWorkbook.Save
Workbooks(MyFile).Close SaveChanges:=True
MyFile = Dir
Loop
'turns settings back on that you turned off before looping folders
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual
MsgBox "Done!"
End Sub
For anyone interested, I found an alternative which I managed to adapt and does exactly what I want:
Sub Loop_Example()
Dim MyFolder As String
Dim file As Variant, wb As Excel.Workbook
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
MyFolder = .SelectedItems(1)
Err.Clear
End With
Application.ScreenUpdating = False
For Each file In Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & startFolder & "*.xl*"" /S /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
Set wb = Workbooks.Open(file)
ActiveWorkbook.Save
wb.Close SaveChanges:=True
Set wb = Nothing
Next
Application.ScreenUpdating = True
MsgBox "Done!"
End Sub
I am new to VBA and this forum has been very helpful to me. I follow the threads posted on this forum to find answers to my questions and I would like to thank you all for providing awesome solutions.
I am currently working on generating a summarysheet from the excel files posted on SharePoint. I have mapped the sharepoint as a network drive. I am trying to open all files from sharepoint folder one after another, copy the required data from different tabs, paste it to summary sheet and close the file. When I try to run the code, it gives me a run time error 52 as 'bad file name or number'.
I have pasted the part of my code here. Any kind of help in this matter is really appreciated.
Thank you,
Pranav
Option Explicit
Sub GenerateSummary()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim Directory As String
Dim MyFile As String
Dim SummarySheet As Workbook
Set SummarySheet = Workbooks.Add
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then
MsgBox ("You did not select a folder")
Exit Sub
End If
Directory = .SelectedItems(1) & "\"
End With
MyFile = Dir(Directory & "*.xlsx")
Do While MyFile <> ""
Workbooks.Open (Directory & MyFile)
Sheets(Array(1, 2)).Select
Sheets(1).Activate
Sheets(Array(1, 2)).Copy Before:=SummarySheet.Sheets(1)
' Other statistics are calculated and operations are performed here
MyFile = Dir()
ActiveWindow.ActivateNext
ActiveWorkbook.Close
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I save all worksheets in a workbook as individual CSV files.
If I make a change to any of the worksheets and run the macro again, it prompts me with the "A file named ... already exists in this location. Do you want to replace it?".
If I click Yes, the prompt comes up for every worksheet. If I click no, the macro throws an error.
Is there a way to avoid the prompt?
Sub CSVAutomation()
Dim ws As Worksheet, wb As Workbook
Dim pathh As Variant
Set wb = ActiveWorkbook
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then 'a folder was picked
pathh = .SelectedItems(1)
End If
End With
If pathh = False Then Exit Sub 'no folder picked; pathh is false
Application.ScreenUpdating = False
For Each ws In wb.Sheets(Array("01 - Currencies", ...."14 - User Defined
Fields"))
ws.Copy
With ActiveWorkbook
'Application.DisplayAlerts = False 'to avoid overwrite warnings
' pathh is a string (variant) of the path of the folder; does not
need pathh.Path
.SaveAs pathh & "\" & ws.Name, xlCSV
.Close SaveChanges:=False
End With
Next ws
Application.ScreenUpdating = True
End Sub
Check my comment and (as Portland Runner says) you could turn off some alerts
I used this
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.AskToUpdateLinks = False
Using a procedure to put inside and used every time to turn it of and another to turned on helpme a lot with all the alerts.
Sub Alerts(ScreenUpdate As Boolean, DisplayAlerts As Boolean, AutoSecurity As Boolean, AskToUpdate As Boolean)
Application.ScreenUpdating = ScreenUpdate
Application.DisplayAlerts = DisplayAlerts
Application.AutomationSecurity = IIf(AutoSecurity, msoAutomationSecurityForceDisable, msoAutomationSecurityByUI)
Application.AskToUpdateLinks = AskToUpdate
End Sub