2016-09-17 43 views
1

我从模板创建工作簿。该模板已经包含了所需的代码模块。我试图获得对代码模块之一的引用,这是代码需要导入到的代码模块的引用(代码总是不同的,因此有一个.bas文件不会在这里工作,因为会有成百上千个代码模块)。使用C访问特定的VBA代码模块

我可以方便地访问使用

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); 

我可以只循环模块并通过测试名称相等来得到它,但必须有一种方法可以在一行代码中检索它。

回答

1

使用VBComponents收集的Item方法,通过名称或数字索引检索现有的VBComponent:

VBIDE.VBComponent component = excelWorkbook.VBProject.VBComponents.Item("Methods"); 
VBIDE.CodeModule module = component.CodeModule; 
+0

就想通了这一点,并进行测试。谢谢你的确认 – dinotom