There.
I need to run an Excel VBA macro 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 found to first confirm the number of files in the folder.
Here's the code that has been suggested to me to open, protect, save and close a single file (however, again, I am looking to do this for 50 or so multiple files).
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
Can this be modified, or do I need new code? Can someone help me?
Thank you!
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
Exit Sub
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
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
CleanExit:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.