【问题标题】:Excel.Application error in Visual Studio Express (Visual Basic)Visual Studio Express (Visual Basic) 中的 Excel.Application 错误
【发布时间】:2016-09-30 15:31:17
【问题描述】:

使用 Excel 2010、Visual Studio Express 2013。

我在 Visual Studio for Microsoft Excel 14.0 中添加了引用对象库

Imports Microsoft.Office.Core
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim oXL As Excel.Application
        Dim oWB As Excel.Workbook
        Dim oSheet As Excel.Worksheet
        Dim oRng As Excel.Range

        ' Start Excel and get Application object.
        oXL = CreateObject("Excel.Application")
        oXL.Visible = True
    End Sub
End Class

但是它给了我以下错误:

类型“Excel.Application”未定义。
类型“Excel.Workbook”未定义。
类型“Excel.Worksheet”未定义。
类型“Excel.Range”未定义。

如果我在 Excel 版本中使用了错误的参考库,请说明如何将正确的对象库添加到列表中。

【问题讨论】:

    标签: vb.net visual-studio-2013 excel-2010


    【解决方案1】:

    您导入了错误的命名空间。

    改变

    Imports Microsoft.Office.Core
    

    Imports Microsoft.Office.Interop
    

    如果您尚未添加对 Microsoft Excel 15.0 对象库的引用(将 15.0 替换为您的版本)

    您可以使用正确的类型来代替后期绑定

    ' using the fully-qualified class name as an example.
    ' Excel.Application would work just fine because Microsoft.Office.Interop is imported
    Dim oXL As Microsoft.Office.Interop.Excel.Application
    Dim oWB As Excel.Workbook
    Dim oSheet As Excel.Worksheet
    Dim oRng As Excel.Range
    
    ' Start Excel and get Application object.
    oXL = New Excel.Application()
    ' note that you have proper intellisense now because oXl is no longer just an Object.
    oXl.Visible = True
    

    最后,要正确清理您的 Excel 引用,因为它是一个 COM 对象,请将其放在您完成对象的代码中(例如,在关闭表单时)。为您创建的每个 COM 对象执行此操作。

    System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL)
    

    【讨论】:

      【解决方案2】:

      想通了。之前的代码来自https://support.microsoft.com/en-us/kb/301982。但是,当我以以下方式编辑代码时,错误消失了。

      Imports Microsoft.Office.Core
      
      Public Class Form1
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      
          Dim oXl As Object
          Dim oWB As Object
          'Dim oXL As Excel.Application
          'Dim oWB As Excel.Workbook
          'Dim oSheet As Excel.Worksheet
          'Dim oRng As Excel.Range
      
          ' Start Excel and get Application object.
          oXL = CreateObject("Excel.Application")
          oXL.Visible = True
      End Sub
      End Class
      

      【讨论】:

      • 这是使用后期绑定。由于 oXl 是一个对象,您可以在该行中添加任何内容 oXL.Visible = True,例如 oXL.Visib = True,并且不会出现任何编译错误。但它会在运行时引发异常。出于这个原因,人们将Option Strict On 放在代码顶部,以指出此类潜在问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2023-03-22
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多