简体   繁体   English

这个VBA代码的C#等价物是什么?

[英]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... 我有这个VBA代码刷新excel表上的数据连接,我正在更新代码和C#的可靠性,而不是Visual Basic ...

So my question is what is the C# equivalent of this VBA code : 所以我的问题是这个VBA代码的C#等价物是什么:

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! 我已经尝试了C#中的逻辑等效,但它没有工作......非常感谢任何帮助!

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" 在这里,错误来自于Connections ,其中显示“不可调用的memer'Microsoft.Office.Interop.Excel._Workbook.Connections'不能像方法一样使用”

Workbooks.Open returns a Workbook which has a Connections member that contains a Connections collection . Workbooks.Open返回一个Workbook ,该Workbook具有包含Connections集合Connections成员。 You can access a single item of those connections using the Item method. 您可以使用Item方法访问这些连接中的单个项目。

So it should probably look like this: 所以它应该看起来像这样:

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

In VB, you are permitted to designate one of the properties or methods of a class as the 'default' member. 在VB中,您可以将类的一个属性或方法指定为“默认”成员。 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. 然后,您可以使用该类的实例的任何标识符“as-if”它是方法名称,它将自动调用/访问默认成员。

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). 在这种情况下, Connections是一个集合,几乎所有VBA集合类的默认成员都是名为Item的方法,它通过索引(数字或名称)返回指定的项目。 So, in VB, these two are equivalent: 所以,在VB中,这两个是等价的:

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. C#与默认成员的概念不同,因此您无法使用第一种语法。 The second syntax is just a normal member access, though, so it works fine. 第二种语法只是普通的成员访问,所以它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM