Open Password Protected Workbook with VBA

2020-08-01 04:55发布

I have wb1 and wb2. wb1 is used for data entry and wb2 is used to record that data. wb2 is password protected (let's say with "password").

The VBA below is in wb1 and is run on a button click. As it is now, a box pops up requesting the password for wb2 before the VBA is done running. Is there a way to use VBA to enter "password" in that box?

I'm fairly new to VBA, so I'm open to other suggestions as well. Thanks!

Sub OpenClose()

Application.ScreenUpdating = False

Dim wb1 As Workbook
Dim wb2 As Workbook

Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open("C:\Users...")  'I have taken out the rest of the file path

wb1.Activate
    Sheets("Entry").Activate
        Range("A1:A5").Select
            Selection.Copy

wb2.Activate
    Sheets("Log").Activate
        Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, _
            SkipBlanks:=False, Transpose:=True

wb2.Save
wb2.Close

Set wb1 = Nothing
Set wb2 = Nothing

MsgBox "Logged and saved."

Application.ScreenUpdating = True

End Sub

标签: vba excel
2条回答
兄弟一词,经得起流年.
2楼-- · 2020-08-01 05:26

When opening wb2 pass your "password" argument as the Password parameter:

Set wb2 = Workbooks.Open(Filename:="C:\Users...", Password:="password")

See Workbooks.Open Method (Excel) for more details.

查看更多
来,给爷笑一个
3楼-- · 2020-08-01 05:26

Checkout this code might be resolved your issue for which you looking for

ThisWorkbook.Password = "1"
ThisWorkbook.Save
ThisWorkbook.Close
查看更多
登录 后发表回答