Adjit
Adjit

Reputation: 10305

What is the C# equivalent of this VBA code?

I have this VBA code that refreshes the data connections on an excel sheet, and I am updating the code a bit and like the reliability of C# as opposed to Visual Basic...

So my question is what is the C# equivalent of this VBA code :

Set wb = Workbooks.Open(fileName, 0, True)
wb.Connections(baseName & " POS Report").OLEDBConnection.BackgroundQuery = False
wb.RefreshAll
wb.Connections(baseName & " POS Report").OLEDBConnection.BackgroundQuery = True

I already tried the logical equivalent in C# but it wasn't working... any help is greatly appreciated!

I have the basics down :

Application excel = new Application();
Workbook ob = excel.Workbooks.Open(eBook[i], 0, true);
ob.Connections(baseName + " POS Report").OLEDBConnection.BackgroundQuery = true;

Here the error comes for Connections where it says "Non-invocable memer 'Microsoft.Office.Interop.Excel._Workbook.Connections' cannot be used like a method"

Upvotes: 0

Views: 1113

Answers (2)

Michael Edenfield
Michael Edenfield

Reputation: 28338

In VB, you are permitted to designate one of the properties or methods of a class as the 'default' member. You can then use any identifier for an instance of that class "as-if" it were a method name, and it will automatically call/access the default member.

In this case, Connections is a collection, and the default member of almost all VBA collection classes is a method called Item which returns the specified item, by index (number or name). So, in VB, these two are equivalent:

WorkbookConnection x = wb.Connections("foo")
WorkbookConnection x = wb.Connections.Item("foo")

C# doesn't have the same concept of a default member, so you can't use the first syntax. The second syntax is just a normal member access, though, so it works fine.

Upvotes: 1

poke
poke

Reputation: 388313

Workbooks.Open returns a Workbook which has a Connections member that contains a Connections collection. You can access a single item of those connections using the Item method.

So it should probably look like this:

ob.Connections.Item(baseName + " POS Report").OLEDBConnection.BackgroundQuery = true;

Upvotes: 1

Related Questions