2

这是在F# Excel UsedRange is not Defined上开始的讨论的延续,该问题已通过将 ActiveSheet 对象向下转换为工作表来解决。然而,在这样做时,我遇到了一个新问题:UsedRange 除了标准对象方法之外没有公开任何属性或方法。

我的解决方案引用了 Microsoft.Office.Interop.Excel 和 Microsoft.Office.Tools.Excel.v4.0.Utilities。

open Microsoft.Office.Interop.Excel
open Microsoft.Office.Tools.Excel

let xl = ApplicationClass()
xl.Workbooks.OpenText(fileName)
let wb = xl.Workbooks.Item(1)
let ws = wb.ActiveSheet :?> Worksheet

ws.UsedRange.EntireColumn.AutoFit()
// "The field, constructor or member 'EntireColumn' is not defined".

ws.UsedRange.Sort(xl.Range(sortKey1), XlSortOrder.xlAscending)
// "The field, constructor or member 'Sort' is not defined".

xl.Range("A2").Value <- 1
xl.Range("A2").AutoFill(xl.Range("A2:A" + ws.UsedRange.Rows.Count),
                        XlAutoFillType.xlFillSeries) |> ignore
// "The field, constructor or member 'Rows' is not defined".

ws.UsedRange.
// Intellisense shows only default object members, e.g. Equals, GetEnumerator, etc.

我可以毫无问题地使用 Range:

xl.Range("A1").EntireColumn.Insert() |> ignore

UsedRange 被识别为 Range。向下转换为 Range,Visual Studio 警告我:“这种类型的测试或向下转换将始终保持”。

范围有效。UsedRange 被识别为 Range。因此,UsedRange 应该可以工作。但事实并非如此。我很矛盾。

Visual Studio 2010 高级版,F# 2.0。

我感谢提供的任何见解。谢谢。

4

1 回答 1

4

您确定您的 F# 项目引用了所有必要互操作程序集的正确版本吗?UsedRange我刚刚在 F# 脚本文件中尝试了您的代码,添加以下行后我可以看到正常的成员:

#r "office.dll"
#r "Microsoft.Office.Interop.Excel.dll"

我可以看到成员喜欢EntireColumn并且Sort它只抱怨片段中的一行试图+在字符串和整数上使用:

xl.Range("A2").AutoFill(xl.Range("A2:A" + (string ws.UsedRange.Rows.Count)), 
                        XlAutoFillType.xlFillSeries) |> ignore 

我在 Visual Studio 2010 中将其作为脚本文件和一个新项目进行了尝试(添加两个引用后,它似乎工作正常)。我添加了对dll安装在 Visual Studio 安装目录中“Visual Studio Tools for Office\PIA”下的引用。

于 2012-10-23T21:32:37.980 回答