我正在从模板创建工作簿。该模板中已包含所需的代码模块。我正在尝试获取对其中一个代码模块的引用,代码需要导入到该模块(代码总是不同的,因此 .bas 文件在这里不起作用,因为它们有数百个)。
我可以使用以下方法轻松访问新代码模块
var codeModule = excelWorkbook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
但我需要访问实例化工作簿变量中现有的“方法”代码模块
//initialize the Excel application and make it invisible to the user.
var excelApp = new Excel.Application
{
UserControl = false,
Visible = false
};
//Create the Excel workbook and worksheet - and give the worksheet a name.
var excelWorkbook = excelApp.Workbooks.Open(TemplateFilePath);
excelWorkbook.Author = Acknowledgements.Author;
var bookPath = excelWorkbook.Path;
//add the macro code to the excel workbook here in the Methods module.
//this adds a new module, how do I access an existing one?
var codeModule = excelWorkbook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
我可以循环遍历模块并通过测试名称相等性来获取它,但必须有一种方法可以在一行代码中检索它。
最佳答案
使用 Item VBComponents 的方法通过名称或数字索引检索现有 VBComponent 的集合:
using VBIDE = Microsoft.Vbe.Interop;
VBIDE.VBComponent component = excelWorkbook.VBProject.VBComponents.Item("Methods");
VBIDE.CodeModule module = component.CodeModule;
关于c# - 使用 C# 访问特定的 VBA 代码模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549657/