c# - 使用 C# 访问特定的 VBA 代码模块

标签 c# vba excel

我正在从模板创建工作簿。该模板中已包含所需的代码模块。我正在尝试获取对其中一个代码模块的引用,代码需要导入到该模块(代码总是不同的,因此 .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/

相关文章:

Excel比较两列

excel - 使用 Excel VBA 宏捕获并保存同一文件中特定区域的屏幕截图

python - 使用 Python 动态地将值写入 Excel 中的单元格

vba - 需要对列Excel vba中的重复文本值进行排名

C# (.Net 2.0) 微优化第 2 部分 : Finding Contiguous Groups within a grid

c# - 这是复制类(class)的好方法吗?

c# - 避免对具有可为空类型/字段的泛型发出警告的最佳方法?

c# - 扩展字符串,转换为数据类型

excel - 如何使用 vba 更新 powerpoint 2010 中嵌入的 Excel 链接

excel - 下拉列表和单元格格式的条件语句