在没有密码提示的情况下从 vba 打开受密码保护的 excel 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40487814/
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-12 11:30:26  来源:igfitidea点击:

Open password protected excel file from vba without the password prompt

excelvbaexcel-vbapassword-protection

提问by Thorka Mae

I have to open an excel file every day and refresh the content to get the newest sales-data. I'd like to automate this with windows task scheduling. Since the excel-file is password protected, i read that the best way is to create another excel file with an workbook_open-macro that opens the desired excel-file. The problem though is, that the code i found still prompts the user to enter the password. I can just hit enter and it'll open then, but why is there still the prompt for it? I am using Excel 365, is there some workaround for this or am i doing something wrong?

我必须每天打开一个 excel 文件并刷新内容以获取最新的销售数据。我想通过 Windows 任务调度来自动执行此操作。由于 excel 文件受密码保护,我读到最好的方法是使用 workbook_open-macro 创建另一个 excel 文件,以打开所需的 excel 文件。但问题是,我找到的代码仍然提示用户输入密码。我可以按回车键然后它会打开,但为什么仍然有提示?我正在使用 Excel 365,是否有一些解决方法或者我做错了什么?

I tried it with ReadOnly:=False and without, nothing changed. If i set ReadOnly:=True, it works, but then i can't save the file after the changes.

我用 ReadOnly:=False 尝试过,没有,没有任何改变。如果我设置 ReadOnly:=True,它可以工作,但更改后我无法保存文件。

This is the code i'm using:

这是我正在使用的代码:

Sub Workbook_Open()
  Application.DisplayAlerts = False
  Workbooks.Open Filename:="Path\file.xlsx", Password:="*****", ReadOnly:=False
  Application.DisplayAlerts = True
  ThisWorkbook.Close SaveChanges:=False
End Sub

回答by Vincent G

Is the workbook password protected or write reserved?

工作簿密码是否受保护或写入保留?

Write reserved files can only be opened in read only without the right password, while password protected can't be opened at all.

写保留文件只能在没有正确密码的情况下以只读方式打开,而受密码保护的文件根本无法打开。

If the workbook is write reserved the right command should be:

如果工作簿被写入保留,则正确的命令应该是:

Workbooks.Open Filename:="Path\file.xlsx", WriteResPassword:="*****", ReadOnly:=False

回答by areklipno

try this:

尝试这个:

  Application.DisplayAlerts = False
  Workbooks.Open "path\file.xlsx", , , , "password"
  Application.DisplayAlerts = True
  ThisWorkbook.Close SaveChanges:=False