F# Excel UsedRange has no Properties or Methods

。_饼干妹妹 提交于 2019-12-12 18:04:03

问题


This is a continuation of the discussion begun on F# Excel UsedRange is not Defined, which has been solved by down-casting the ActiveSheet object to a Worksheet. Upon doing that, however, I was presented with a new problem: UsedRange exposes no properties or methods other than the standard object methods.

My solution has references to Microsoft.Office.Interop.Excel and 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.

I can use Range with no problem:

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

UsedRange is recognized as a Range. Down-casting to Range, Visual Studio warns me: "This type test or downcast will always hold".

Range works. UsedRange is recognized as Range. Therefore, UsedRange should work. But it doesn't. I'm left with contradiction.

Visual Studio 2010 Premium, F# 2.0.

I appreciate any insight offered. Thanks.


回答1:


Are you sure your F# project references the correct versions of all the necessary interop assemblies? I just tried your code in F# script file and I can see members of UsedRange fine after adding the following lines:

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

I can see members like EntireColumn and Sort and it only complains that one line in the snippet is attempting to use + on string and integer:

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

I tried this in Visual Studio 2010 as a script file and also in a new project (after adding the two references, it seems to be working okay). I added reference to the dll that is installed under "Visual Studio Tools for Office\PIA" in the Visual Studio installation directory.



来源:https://stackoverflow.com/questions/13039153/f-excel-usedrange-has-no-properties-or-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!