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.
Related
I am trying to build a data formatter where the user selects a file of type .xlsx and then I format it and save it as type .csv. I am needing to convert the xlsx file to a csv before I can format it. To do this, I couldn't find anything apart from opening the file, copying the used range to a worksheet on the original file, saving that worksheet as csv and then referencing that file. Despite a lack of elegance, this would work fine for the use case. However, I cannot seem to get the copying of the worksheet to be formatted down.
Here's what I'm trying for copying:
Dim active As Worksheet
Set active = ActiveSheet
With Workbooks.Open(myFile)
ActiveSheet.UsedRange.Copy
active.Paste
.Close SaveChanges:=False
End With
This, in theory, should copy the data from the file being opened to the already opened file, but it doesn't.
This works great for me:
As a sub:
Sub ConvertToCSV()
Dim MyFile As String
Dim WBtmp As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
MyFile = "C:\Users\cameron\Documents\IDs.xlsx"
Set WBtmp = Workbooks.Open(MyFile)
With WBtmp
.SaveAs Replace(MyFile, ".xlsx", ""), xlCSV
.Close
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Or as a function
Sub TestFunc()
fConvertToCSV "C:\Users\cameron\Documents\IDs.xlsx"
End Sub
Function fConvertToCSV(MyFile As String)
Dim WBtmp As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set WBtmp = Workbooks.Open(MyFile)
With WBtmp
.SaveAs Replace(MyFile, ".xlsx", ""), xlCSV
.Close
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Function
I've got a workbook where I am creating a button that allows to save two specific sheets without formula's (the purpose being that the sheets are going to be send to partners and costumers). I would like the sheets to be saved in a single document somewhere on my computer, and still have the current "design" with colors, setup etc.
I've currently written this code, which does everything that I've described, except deleting the formulas...
Sub SaveAsValues()
Dim ws As Worksheet
Worksheets(Array("frontpage", "mobile")).Copy After:= ws.Worksheets
With ActiveWorkbook
.SaveAs Filename:= "C:XXXX" & "NAME", FileFormat:= xlOpenXMLWorkbook
.Close savechanges = False
End With
End Sub
Hope you can help :-)
I have a sheet I use something similar for, I'll adjust the code a bit to work with your scenario. If you don't want the settings to change, delete the TurnOnFunctions & TurnOffFunctions subs.
This code will only break the links, not necessarily all the formulas. So if a formula references another spreadsheet it will be a static value; however, if it is a simple formula that stays within the spreadsheet it will stay that way.
Also add your workbook name to the respective area.
Sub NewWorkbooks()
'This will make seperate workbooks for each of the tabs listed
Dim wb As Workbook
Dim NewBook As Workbook
Dim ws As Worksheet
Call TurnOffFunctions
Set wb = ActiveWorkbook
For Each ws In Workbooks("YOUR WORKBOOK NAMR"). _
Worksheets(Array("frontpage", "mobile"))
ws.Copy
Set NewBook = ActiveWorkbook
With NewBook
Call break_links(NewBook)
.SaveAs Filename:="C:XXXX" & "NAME", FileFormat:=xlOpenXMLWorkbook
.Close SaveChanges:=False
End With
Next
Call TurnOnFunctions
End Sub
Sub break_links(ByRef wb As Workbook)
Dim Links As Variant
On Error Resume Next
Links = wb.LinkSources(Type:=xlLinkTypeExcelLinks)
On Error GoTo 0
If Not IsEmpty(Links) Then
For i = 1 To UBound(Links)
wb.BreakLink _
Name:=Links(i), _
Type:=xlLinkTypeExcelLinks
Next i
End If
End Sub
Private Sub TurnOffFunctions()
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
End Sub
Private Sub TurnOnFunctions()
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
You can use yours too with this mod (untested):
Sub SaveAsValues()
Dim ws As Worksheet
Worksheets(Array("frontpage", "mobile")).Copy After:= ws.Worksheets
Call break_links ActiveWorkbook
With ActiveWorkbook
.SaveAs Filename:= "C:XXXX" & "NAME", FileFormat:= xlOpenXMLWorkbook
.Close savechanges = False
End With
End Sub
Sub break_links(ByRef wb As Workbook)
Dim Links As Variant
On Error Resume Next
Links = wb.LinkSources(Type:=xlLinkTypeExcelLinks)
On Error GoTo 0
If Not IsEmpty(Links) Then
For i = 1 To UBound(Links)
wb.BreakLink _
Name:=Links(i), _
Type:=xlLinkTypeExcelLinks
Next i
End If
End Sub
I have a code that extracts a tab from a workbook and saves the tab as a separate sheet. Everything is working fine for me, except for the fact that the formulas are also extracted to the new sheet. How can I change the code mentioned below to save the sheet in the same format, but without any formulas?
Sub PrintFile2()
'check if folder exists
If Dir("C:\Excel Workpaper\", vbDirectory) = "" Then
MkDir "C:\Excel Workpaper\"
End If
'print to defined folder
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wb As Workbook
Sheets("Calculations").Copy
Set wb = ActiveWorkbook
With wb
.SaveAs "C:\Excel Workpaper\ " & Range("B7").Text & " - Excel Workpaper",
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
Application.ScreenUpdating = True
.Close False
End With
End Sub
Check this snippet, this code will change formula to values.
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
sh.Select
With sh.UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
Next sh
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
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