2016-09-17 77 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