使用 VBA 打开受密码保护的工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34074526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:06:03  来源:igfitidea点击:

Open Password Protected Workbook with VBA

excelvbaexcel-vba

提问by Rich

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").

我有 wb1 和 wb2。wb1 用于数据输入,wb2 用于记录该数据。wb2 受密码保护(比方说“密码”)。

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?

下面的 VBA 在 wb1 中,并在单击按钮时运行。就像现在一样,在 VBA 运行完成之前,会弹出一个框,要求输入 wb2 的密码。有没有办法使用 VBA 在那个框中输入“密码”?

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

我对 VBA 还很陌生,所以我也愿意接受其他建议。谢谢!

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

回答by Graham

When opening wb2pass your "password" argument as the Passwordparameter:

打开时wb2将您的“密码”参数作为Password参数传递:

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

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

有关更多详细信息,请参阅Workbooks.Open 方法 (Excel)

回答by user9564246

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

签出此代码可能会解决您正在寻找的问题

ThisWorkbook.Password = "1"
ThisWorkbook.Save
ThisWorkbook.Close