.net - 在 VB.NET 或 C# 中编写 VBA Excel 宏,首先进行早期绑定(bind),然后进行后期绑定(bind)

标签 .net .net-4.0 vsto ms-office

每次看到使用.NET的办公自动化示例,使用的语言都是VB.NET。

这是因为最初,自动化 Office 应用程序(如 Excel)只能在宏中使用 VB 脚本来完成,而编写这些宏的人自然倾向于使用 VB.NET,或者是否有理由不使用 C# for Office自动化?

看起来我可以通过 C# 实例化 Excel 类,就像使用 VB.NET 中的 CreateObject 一样。

excel = Type.GetTypeFromProgID("Excel.Application");

如果您必须使用 Excel Automation 编写 .NET 程序,您会使用什么语言?除了可能有一些 VB.NET 示例之外,是否有任何理由避免使用 C#?

编辑:

我正在考虑编写显式引用 Microsoft Excel 对象库和显式实例化 Excel 类 Application 对象的代码,然后在程序经过基本测试后,修改代码以使用后期绑定(bind)以允许应用程序与不同版本的 Excel 一起运行。

代码会完全不同吗?

例如,使用早期绑定(bind)我可以做到这一点......

var excel2  = new Microsoft.Office.Interop.Excel.Application();
excel2.Visible = true;

在后期出价中,我是否会被迫使用像这样完全不同的代码?

excel = Type.GetTypeFromProgID("Excel.Application");
excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter);

最佳答案

尽管还有更多可用于 VB.NET 的代码示例,但我已经成功地使用了这两种方法。

我立即想到的一个区别是,API 方法似乎包含大量可选方法参数,而 C# <4 中不存在这些参数,因此您会发现自己正在执行以下操作:

object missing = Type.Missing;
Excel.Application xl = new Excel.Application();
xl.Workbooks.Open(fileName, 0, true, 5, "", "", true, 
            Excel.XlPlatform.xlWindows, missing, missing, missing, 
            missing, missing, missing, missing);

在 VB.NET 中不仅仅是这样:

Dim xl As New Excel.Application()
xl.Workbooks.Open(fileName, 0, True, 5, "", "", true, Excel.XlPlatform.xlWindows)

VB.NET 提供的一些语法糖对于编写使用 OLE 自动化库或互操作程序集的应用程序的简洁性有很大帮助。

编辑:至于早期绑定(bind)与后期绑定(bind),我不能说我有任何后期绑定(bind)的经验。 This article讨论了一种为 Office 应用程序的多个版本安全实现后期绑定(bind)的方法。

报价from the article :

...you can start developing your add-in using interops for the highest version of the Office application. When this is done, you can replace early-binding calls to the features introduced in this Office version with late binding calls and make sure these calls work. Then you can replace the interop assemblies referenced by your project with the interop for a previous version of the application and reiterate the procedure. Kind of refactoring. Whether this approach is useful or not, this is you who decides

关于.net - 在 VB.NET 或 C# 中编写 VBA Excel 宏,首先进行早期绑定(bind),然后进行后期绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12375613/

相关文章:

wpf - WPF DatePicker 奇怪的外观

excel - 如何正确捕获 Excel 单元格边框?

c# - xUnit.net:为什么这两个等效测试有不同的结果?

c# - 为什么可为空的 KeyValuePair<,> 没有键属性?

visual-studio-2010 - 如何在.NET 4.0中使用Fluent NHibernate?

c# - 在 .net 4 上使用异步等待

c# - 在word自动化中设置列宽抛出异常

c# - 替换 Windows Installer 项目中的 DLL

c# - Web Api IEnumerable 顺序

c# - 扩展 LINQ 以接受可为空的枚举