VBA to create password protected file

2019-09-16 15:35发布

With the below coding, I am able to create a copy of password protected file. But I also want to put the password in newly created file. How can I add password while creating new excel workbook.

Workbooks.Open Filename:=myFileNameDir, Password:="yourpassword", UpdateLinks:=0
Set ws1 = Worksheets("OJT Plan")
ws1.Activate
filen = TextBox3.Text & "_" & TextBox59 & "_" & VBA.Format(Now, "MMddyyyyhmmss AM/PM ")
ws1.SaveAs Sheet1.Range("V3").Value & filen & ".xlsx"
Worksheets.Add(after:=Worksheets(Worksheets.Count)).Name = "Details"
Set ws13 = Worksheets("Details")

1条回答
Deceive 欺骗
2楼-- · 2019-09-16 16:24

If you look at the documentation you will see there are two password arguments for the SaveAs command

ws1.SaveAs FileName:=Sheet1.Range("V3").Value & filen & ".xlsx", _
           Password:="yourpassword", _                                
           WriteResPassword:="yourreadonlypassword"

The difference in these two password arguments is explained in the docs:

Password: A case-sensitive string (no more than 15 characters) that indicates the protection password to be given to the file.

WriteResPassword: A string that indicates the write-reservation password for this file. If a file is saved with the password and the password isn't supplied when the file is opened, the file is opened as read-only.

查看更多
登录 后发表回答