The first one is easy - VBComponents.Add
returns a VBComponent
. You can just inspect the .Name
property:
var module = excelFile.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
Debug.WriteLine(module.Name);
The second one is a bit trickier. You'll need to loop through all of the VBComponents and test for the 2 things that are unique to the Workbook object. It will have a .Type
of vbext_ct_Document
and 134 properties in its .Properties
collection by default:
VBComponent thisWorkbook;
foreach (var module in excelFile.VBProject.VBComponents)
{
var test = module as VBComponent;
if (test.Type == vbext_ComponentType.vbext_ct_Document &&
test.Properties.Count == 134)
{
thisWorkbook = test;
Debug.WriteLine(thisWorkbook.Name);
break;
}
}
EDIT:
The Linq solution looks like this, but it's possible that you could leave dangling Interop references this way. If you want to try it, it can't hurt - but it would be the first place I'd look if Excel doesn't shut down properly:
var thisWorkbook =
(excelFile.VBProject.VBComponents).Cast<VBComponent>()
.First(x => x.Type == vbext_ComponentType.vbext_ct_Document &&
x.Properties.Count == 134);
EDIT2: As pointed out by @Mat'sMug in the comments, the property count is specific to the version - the value above is probably specific to Excel 2013. For a new workbook, the ThisWorkbook module will be the one with the highest property count. This should work on any version:
VBComponent thisWorkbook = null;
foreach (var component in excelFile.VBProject.VBComponents.Cast<VBComponent>())
{
if (thisWorkbook == null || component.Properties.Count > thisWorkbook.Properties.Count)
{
thisWorkbook = component;
}
}
Debug.WriteLine(thisWorkbook.Name);
Linq:
var thisWorkbook =
excelFile.VBProject.VBComponents.Cast<VBComponent>()
.Aggregate((p, x) => (p.Properties.Count > x.Properties.Count ? p : x));