使用Application.Intersect我为什么会出现Type Mismatch

时间:2013-08-28 13:13:10

标签: vb.net excel excel-interop

这是我的代码。我认为这应该有用;我正在保存wb并尝试使用wb.Application获取Excel Application对象。它确实有效,但XLApp.Intersect失败并出现“Type Mismatch”错误。

Dim wb As Object

Sub First()
    Dim XLApp As Object
    XLApp = CreateObject("Excel.Application")
    wb = myXL.XLApp.Workbooks.Add()
End Sub

Sub Second()
    Dim XLApp as object = wb.Application
    Dim rg as object = XLApp.Intersect(ws.UsedRange, ws.Columns("B"))
End Sub

是否可以从工作簿中获取Excel Application并仍然使用Intersect方法?

我还尝试将XLapp保存到全局变量并重新使用它,但这也不起作用;同样的错误。

我正在尝试避免使用Excel Interop引用来保持与旧版Excel的向后兼容性。

MSDN Library _Application.Intersect Method

我注意到我的应用程序对象是类型:Microsoft.Office.Interop.Excel.ApplicationClass

1 个答案:

答案 0 :(得分:0)

varocarbas的答案让我想到了我正在使用的各种类型。所以我尝试了对象Dim ObjRange1 As Object和声明类型Dim rg1 As Excel.Range

的各种组合

这是我测试过的代码,除了最后一个给出“类型不匹配”错误的代码之外它工作得很好。

Sub testXL1()

    Dim XLApp As Object
    Dim wb As Object
    Dim ws As Object

    XLApp = CreateObject("Excel.Application")
    XLApp.visible = True
    wb = XLApp.Workbooks.Add()
    XLApp = wb.application
    ws = wb.worksheets(1)
    ws.cells(1, 1) = "First"
    ws.cells(2, 2) = "hello"

    'this works fine
    Dim rg1 As Microsoft.Office.Interop.Excel.Range
    Dim rg2 As Microsoft.Office.Interop.Excel.Range
    Dim rg3 As Microsoft.Office.Interop.Excel.Range
    rg1 = ws.usedRange
    rg2 = ws.columns("B")
    rg3 = XLApp.Intersect(rg1, rg2)
    rg3.Select()

    'this works fine
    Dim rg4 As Object
    rg4 = XLApp.Intersect(rg1, rg2) 'Public member 'Intersect' on type 'Object()' not found.
    rg4.Select()

    'this works fine
    Dim ObjRange1 As Object = ws.usedRange
    Dim ObjRange2 As Object = ws.columns("B")
    Dim rg5 As Microsoft.Office.Interop.Excel.Range
    rg5 = XLApp.Intersect(ObjRange1, ObjRange2)
    rg5.Select()

    'this works fine
    Dim ObjRange3 As Object
    ObjRange3 = XLApp.Intersect(ObjRange1, ObjRange2)
    ObjRange3.Select()

    'this give a Type Mismatch error
    ObjRange3 = XLApp.Intersect(ws.usedRange, ws.columns("B"))
    ObjRange3.Select()


End Sub

所以我想答案是在将范围设置为ObjRange3 = XLApp.Intersect(ObjRange1, ObjRange2)

中的参数之前将范围设置为对象变量

varocarbas回答与使用DirectCast

有关
rg = DirectCast(XLApp, Microsoft.Office.Interop.Excel.Application).Intersect(...

Understanding the Excel Object Model from a .NET Developer's Perspective