Excel Linksources / no object array enumerator

A

Ali Tahbaz

I'm having trouble iterating through LinkSources in an Excel workbook
using C#. I first wrote the below code in VBA to get a quick, correct
result,

Dim x As Variant
For Each x In ThisWorkbook.LinkSources
Debug.Print x
Next

but am so far unable to successfully convert the code to workable
C# syntax. C#'s compiler complains

"foreach statement cannot operate on variables of type 'object'
because 'object' does not contain a definition for 'GetEnumerator', or
it is inaccessible"

when I try to use the below code :

foreach(string Src in wb.LinkSources(rfl.Missing.Value)) {
Console.WriteLine(Src);
}

What can I do to list the links in a workbook from C#?

Thanks in advance,
Ali Tahbaz, MCSD
 
A

Ali Tahbaz

The link to a generic MS help file on .net+ Excel was interesting,
but has little to do with the specific question I asked. (There is no
reference to late bound object arrays returned to a C# client.)
Has anyone run into this problem and overcome it?

Ali
 
A

Ali Tahbaz

For anyone else who needs to parse a variant array returned from Excel
or elsewhere, here is what I've found that works (through trial and error) :
(My specific problem was with returning the results of Excel's
LinkSources method.)

object src = (object)wb.LinkSources(Excel.XlLinkType.xlLinkTypeExcelLinks);
System.Array variantArray = (Array)src;
for(int i=1;i<=variantArray.Length;i++) {
Console.WriteLine(variantArray.GetValue(i).ToString());
}

C# likes to catch the variant array as a plain object type. Once you've
got the object type you can cast it to a System.Array and iterate through
the contained items.

Ali Tahbaz, MCSD
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top