简体   繁体   中英

Macro to save password protected file

I wrote the following macro in Excel2010 for an action button to save a given sheet as password protected file on a shared drive.

Private Sub Report_Click()

 Sheets("sheetname").SaveAs Filename:="\\shared_folder_path\master" & Sheets("sheetname").Range("A2"), _
                            FileFormat:=52, _
                            Password:="password", _
                            WriteResPassword:="password", _
                            ReadOnlyRecommended:=False, _
                            CreateBackup:=False

End Sub

The problem is that I get a Run-time error '1004'

I believe it has something to do with your FileName path.

I tested it and just used a path this links to my desktop and it saved fine. Try the same test replacing the path with a path to your desktop.

You will need to add the assigned Drive letter your computer uses to the network folder path possibly.

A cleaner way of presenting the same code is below with the

 Private Sub Report_Click()
      Sheets("Sheet1").SaveAs _
           Filename:="C:\Users\user1\Desktop\" & Sheets("Sheet1").Range("A2"), _
           FileFormat:=52, _
           Password:="password", _
           WriteResPassword:="password", _
           ReadOnlyRecommended:=False, _
           CreateBackup:=False
 End Sub

Also have a look at this How to programmatically save a file to a network drive in Excel for a basic example.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM