Cod*_*ode 1 vb.net excel-2010 visual-studio-2013
使用 Excel 2010、Visual Studio Express 2013。
我在 Visual Studio 中为 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
Run Code Online (Sandbox Code Playgroud)
但是它给了我以下错误:
未定义类型“Excel.Application”。
未定义类型“Excel.Workbook”。
未定义类型“Excel.Worksheet”。
未定义类型“Excel.Range”。
如果我为 excel 版本使用了错误的参考库,请说明如何将正确的对象库添加到列表中。
您导入了错误的命名空间。
改变
Imports Microsoft.Office.Core
Run Code Online (Sandbox Code Playgroud)
到
Imports Microsoft.Office.Interop
Run Code Online (Sandbox Code Playgroud)
如果尚未添加对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
Run Code Online (Sandbox Code Playgroud)
最后,为了正确清理你的 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)
Run Code Online (Sandbox Code Playgroud)