Excel vba 在工作簿打开时自动运行宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27212952/
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
Excel vba auto run macro on workbook open
提问by WKI
I have a Sub WorkSheet_Change(ByVal Target As Range)
which i want to automatically run for all users. The problems is these users barely know or bother to enable macro when entering data. Is there a way to force macro to automatically run on this workbook? I have seen an article about an event called Workbook_Open ()
but i have no idea on how to use it. Any help?
我有一个Sub WorkSheet_Change(ByVal Target As Range)
我想为所有用户自动运行的。问题是这些用户在输入数据时几乎不知道或费心启用宏。有没有办法强制宏在这个工作簿上自动运行?我看过一篇关于名为事件的文章,Workbook_Open ()
但我不知道如何使用它。有什么帮助吗?
回答by BobbitWormJoe
For security reasons, you can't force a workbook to enable macros without explicit input from the user.
出于安全原因,您不能在没有用户明确输入的情况下强制工作簿启用宏。
What you can do though, is set all the sheets the user would need to hidden. Then create a visible sheet with just a textbox or something that says "Please enable macros to continue." Then use the Workbook_Open
event to hide that sheet and unhide the other sheets.
但是,您可以做的是设置用户需要隐藏的所有工作表。然后创建一个仅包含文本框或显示“请启用宏以继续”的可见工作表。然后使用该Workbook_Open
事件隐藏该工作表并取消隐藏其他工作表。
Additionally, use the Workbook_BeforeSave
event to re-hide the sheets when the user saves the spreadsheet, so the check has to be performed every time.
此外,Workbook_BeforeSave
当用户保存电子表格时,使用该事件重新隐藏工作表,因此每次都必须执行检查。
Additional tip: When hiding sheets using VBA, try to use xlSheetVeryHidden
versus xlSheetHidden
. This means the users won't be able to unhide them from excel like a normal hidden sheet (so you can avoid a stubborn user using that loophole).
附加提示:使用 VBA 隐藏工作表时,请尝试使用xlSheetVeryHidden
vs xlSheetHidden
. 这意味着用户将无法像普通隐藏表一样从 excel 中取消隐藏它们(因此您可以避免使用该漏洞的顽固用户)。
EDIT: Here's some sample code, with made-up sheet names of course:
编辑:这是一些示例代码,当然还有合成的工作表名称:
Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Worksheets("Data1").Visible = xlSheetVisible
Worksheets("Data2").Visible = xlSheetVisible
Worksheets("Welcome").Visible = xlSheetVeryHidden
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Worksheets("Welcome").Visible = xlSheetVisible
Worksheets("Data1").Visible = xlSheetVeryHidden
Worksheets("Data2").Visible = xlSheetVeryHidden
End Sub
Private Sub Workbook_Open()
Worksheets("Data1").Visible = xlSheetVisible
Worksheets("Data2").Visible = xlSheetVisible
Worksheets("Welcome").Visible = xlSheetVeryHidden
End Sub