VB.NET后期绑定

时间:2016-09-12 20:07:10

标签: vb.net excel binding

两天来,我无法将VB代码更改为EARLY绑定:

Dim Excel02 = New Microsoft.Office.Interop.Excel.Application()
Excel02.Application.WindowState = Excel02.XlWindowState.xlMaximized
Dim Excel02Workbook As Microsoft.Office.Interop.Excel.Workbook
Excel02Workbook = Excel02.Workbooks.Open("C:\Eigene-D\DS-GM\DS-GM-2016.xlsm")
Dim Excel02WorkSheet01 As Microsoft.Office.Interop.Excel.Worksheet
Excel02WorkSheet01 = CType(Excel02Workbook.Sheets("eBay"), Microsoft.Office.Interop.Excel.Worksheet)
Excel02WorkSheet01.Activate()

Excel02.Visible = True

Dim RowEinfuegen1 As Microsoft.Office.Interop.Excel.Worksheet = CType(Excel02WorkSheet01.Rows(10).Resize(5).Insert, Microsoft.Office.Interop.Excel.Worksheet)    

最后一行是问题,请帮助。

1 个答案:

答案 0 :(得分:0)

我同意,最后是个问题。但是你想要完成什么?

Dim RowEinfuegen1 As Microsoft.Office.Interop.Excel.Worksheet =
    CType(Excel02WorkSheet01.Rows(10).Resize(5).Insert, 
        Microsoft.Office.Interop.Excel.Worksheet)

您正在尝试投射的对象

Excel02WorkSheet01.Rows(10).Resize(5).Insert

似乎是一个布尔

Debugger screen

但是你将它作为工作表进行投射。演员可能不是你想要的。我写了一些代码来在Excel02中创建一个新工作表,并插入范围。也许这就是你想要做的。

Dim Excel02 = New Microsoft.Office.Interop.Excel.Application()
Excel02.Application.WindowState = Microsoft.Office.Interop.Excel.XlWindowState.xlMaximized
Dim Excel02Workbook As Microsoft.Office.Interop.Excel.Workbook
Excel02Workbook = Excel02.Workbooks.Open("C:\Temp\DS-GM-2016.xlsx")
Dim Excel02WorkSheet01 As Microsoft.Office.Interop.Excel.Worksheet
Excel02WorkSheet01 = CType(Excel02Workbook.Sheets("eBay"), Microsoft.Office.Interop.Excel.Worksheet)
Excel02WorkSheet01.Activate()

Excel02.Visible = True

Dim rowsRange As Microsoft.Office.Interop.Excel.Range = Excel02WorkSheet01.Rows(10)
Dim resizedRange As Microsoft.Office.Interop.Excel.Range = rowsRange.Resize(5)

Dim newBook As Microsoft.Office.Interop.Excel.Workbook = Excel02.Workbooks.Add()
Dim newSheet As Microsoft.Office.Interop.Excel.Worksheet = newBook.Sheets.Add()
Dim newRange As Microsoft.Office.Interop.Excel.Range = newSheet.Rows(1)
newRange.Insert(0, resizedRange)

请记住,您需要摆脱内存中的非托管对象(C#GC不会(立即)自动执行此操作)。见how

Marshal.ReleaseComObject(newRange)
Marshal.ReleaseComObject(newSheet)
Marshal.ReleaseComObject(newBook)
Marshal.ReleaseComObject(resizedRange)
Marshal.ReleaseComObject(rowsRange)
Marshal.ReleaseComObject(Excel02WorkSheet01)
Marshal.ReleaseComObject(Excel02Workbook)
Marshal.ReleaseComObject(Excel02)