简体   繁体   English

在工作簿上打开Excel VBA自动运行宏

[英]Excel vba auto run macro on workbook open

I have a Sub WorkSheet_Change(ByVal Target As Range) which i want to automatically run for all users. 我有一个Sub WorkSheet_Change(ByVal Target As Range) ,我想为所有用户自动运行。 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. 我看过一篇有关事件的文章,称为Workbook_Open ()但我不知道如何使用它。 Any help? 有什么帮助吗?

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事件重新隐藏Workbook_BeforeSave表,因此必须每次执行检查。

Additional tip: When hiding sheets using VBA, try to use xlSheetVeryHidden versus xlSheetHidden . 附加提示:使用VBA隐藏工作表时,请尝试使用xlSheetVeryHiddenxlSheetHidden 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). 这意味着用户将无法像普通的隐藏工作表一样将其从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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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