[RESOLVED] Late binding error when accessing an excel spreadsheet
When I have Options Strict On, I get a Late Binding error when trying to access cells in an Excel Spreadsheet. The error goes away if I set Options Strict Off, but I would prefer to keep it on. Here is a snip-it of code.
Code:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim APP As New Excel.Application
Dim worksheet As Excel.Worksheet
Dim workbook As Excel.Workbook
Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
TextBox1.Text = worksheet.Cells(1, 1).Value.ToString ' Late Binding Error
TextBox2.Text = worksheet.Cells(1, 2).Value.ToString ' Late Binding Error
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
workbook = APP.Workbooks.Open(Application.StartupPath & "\temp.xlsx")
worksheet = CType(workbook.Worksheets("sheet1"), Excel.Worksheet)
End Sub
End Class
Note, I have added a reference to Microsoft Excel 14.0 Object Library. Any idea on how to resolve this?
Re: Late binding error when accessing an excel spreadsheet
This should do it.
Code:
Dim Cells As Excel.Range
...
Cells = worksheet.Range("A1")
TextBox1.Text = Cells.Value.ToString
Cells = worksheet.Range("A2")
TextBox2.Text = Cells.Value.ToString
Re: Late binding error when accessing an excel spreadsheet
Unfortunately, it still has the same problem.
Re: Late binding error when accessing an excel spreadsheet
Quote:
Originally Posted by
John_SC
Unfortunately, it still has the same problem.
Try casting the cells to Excel.Range
Code:
DirectCast(worksheet.Cells(1, 1), Excel.Range).Value.ToString
instead of:
Code:
Cells.Value.ToString
Re: Late binding error when accessing an excel spreadsheet
Quote:
Originally Posted by
John_SC
Unfortunately, it still has the same problem.
Not sure what you're doing differently then. I literally pasted your code, made my changes and tested with a spreadsheet I had. My Imports statement was slightly different
Code:
Imports Microsoft.Office.Interop
though I just tried your's and it worked as well. I'm using 2013 and there are no late binding errors now with Option Strict On.
Re: Late binding error when accessing an excel spreadsheet
Peter's solution worked for me.
Topshots' solution did not. Not sure what the issue is.
Thanks for the help.