单击工作表时运行 excel VBA 函数

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

Run excel VBA function when sheet is clicked

excelvba

提问by puissant

I was wondering if there was a way to run a VBA script when I open a sheet in the workbook.

我想知道当我在工作簿中打开工作表时是否有办法运行 VBA 脚本。

For example, I have a workbook called "Inventory" and I want to run an "InitiateInventoryValues" Function when the "View Inventory" sheet is opened.

例如,我有一个名为“库存”的工作簿,我想在“查看库存”表打开时运行“InitiateInventoryValues”函数。

Can anybody please help me on this?

有人可以帮我吗?

回答by aevanko

Double click the "Workbook" icon in VBE and use this event. It will trigger everytime you activate a different sheet by clicking its tab. If the tab is the one named "View Inventory", your code will run (once) when the sheet is activated:

双击 VBE 中的“工作簿”图标并使用此事件。每次您通过单击其选项卡激活不同的工作表时,它都会触发。如果该选项卡是名为“查看库存”的选项卡,则您的代码将在工作表被激活时运行(一次):

Private Sub Workbook_SheetActivate(ByVal Sh As Object)

If Sh.Name = "View Inventory" Then
    'Do your code
End If

End Sub