vba 动态地将代码添加到新的 Excel 工作表

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

Adding code to new excel sheet dynamically

excelvbaexcel-vbavalidationprogrammatically-created

提问by krishna

I need some help Regarding VBA. In My code I add an excel sheet and rename it and add a validation list to it.I need to run some code on changing value in that validation list.And that must run only on change of that particular cell. If I am not clear please let me know.Please Help me solving this.

我需要一些关于 VBA 的帮助。在我的代码中,我添加了一个 Excel 工作表并重命名它并向其添加一个验证列表。我需要在更改该验证列表中的值时运行一些代码。并且必须仅在更改该特定单元格时运行。如果我不清楚,请告诉我。请帮我解决这个问题。

回答by Peter Albert

Instead of trying to create the individual code for each new worksheet with the Visual Basic Extensibility (see this linkfor further reading), simply use the Workbook wide event Workbook_SheetChange(you need to place it in the ThisWorkbookmodule).

无需尝试使用 Visual Basic 扩展性为每个新工作表创建单独的代码(请参阅此链接以进一步阅读),只需使用工作簿范围事件Workbook_SheetChange(您需要将其放置在ThisWorkbook模块中)。

In this event code first check, if the worksheet which caused the event is one of the newly created worksheets. This can be done most easily, be checking the .Nameof the worksheet.

在此事件代码中,首先检查导致事件的工作表是否是新创建的工作表之一。这可以最容易地完成,检查.Name工作表的。

回答by didierdrogod

you can use SelectionChangeEvent and Changeevent or it is also possible to use the event Thisworkbookmodule. SheetChangeor SheetSelectionChange.

您可以使用SelectionChangeEvent 和Changeevent ,也可以使用 eventThisworkbook模块。SheetChangeSheetSelectionChange