Set password to closed workbook

YasserKhalil

Well-known Member
Joined
Jun 24, 2010
Messages
852
I have searched but didn't find a way to put an external password on closed workbook. Suppose I have closed workbook named "Sample.xlm" .. and I am opening a workbook named "Test.xlm". Is there a code that enables me to put a password on the Sample.xlsm? I mean external password .. I tried the following but got error (method protect of object workbook failed)
VBA Code:
Sub Test()
    Dim wb As Workbook

    Set wb = Workbooks.Open(ThisWorkbook.Path & "\Sample.xlsm")
    wb.Protect Password:="123"
    wb.Close True
End Sub

** I was protecting the Sample workbook with Protect and Share Workbook and I have changed to UnShare. This was the problem of the error that appears.
Now the code is working but when opening the Sample workbook after running the code, I found it unprotected. I expect to get it protected.

Thanks advanced for help
Posted here too
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
** It seems I am wrong too at my approach. This would protect the structure of the workbook not to set the external password as the snapshot displays.
Untitled.png
 
Upvote 0
Solved using this line
VBA Code:
wb.SaveAs Filename:=ThisWorkbook.Path & "\NewSample.xlsm", Password:="123"

But I welcome any other ideas. Such as using API to set the password to the closed workbook without the need to use the SaveAs feature
 
Upvote 0
Hi Yasser,

I think there is some commercial softaware that locks folders (not sure about files) but I have never seen code that does that.

What is the problem with opening the workbook and re-saving it with a password for opeining via SaveAs ?

Regards.
 
Upvote 0

Forum statistics

Threads
1,214,958
Messages
6,122,475
Members
449,087
Latest member
RExcelSearch

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top