I tried to use a line of VBA code to add password to my current open workbook, but after I ran that, then closed and reopened the same file, it did not require the password I added. Can anyone please help me understand why? Thanks in advance!
Sub addPassword()
ThisWorkbook.SaveAs Password:="qq1234"
End Sub
CodePudding user response:
Please, try the next way:
Sub SaveWithPassword()
Dim fileF As Long
Application.DisplayAlerts = False
With ActiveWorkbook
fileF = .FileFormat
.SaveAs Filename:=.FullName, FileFormat:=fileF, Password:="qq1234", CreateBackup:=False
.Close False
End With
Application.DisplayAlerts = True
End Sub
Even if all SaveAs
method parameters are Optional
, there are some things which Excel cannot always guess.
ThisWorkbook
does not mean the active book, except the case when the workbook keeping the code is the active one. The default FileFormat
is the last one used. If it does not matches with the workbook one, Excel is not able to save it.
The above way uses minimum of the necessary parameters and it should not fail...