Click to See Complete Forum and Search --> : Trying to read data from the cells of a pre-existing Excel file


irishman
March 14th, 2008, 11:35 AM
I'm having trouble making this work. I'm trying to open an excel file on the hard drive and read the data that's already in the worksheet. It then plugs the data into some textboxes on the next form. Here's my code for opening and reading the data:

With OpenFileDialog1
.Filter = "XLS files (*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Open Template"
End With
OpenFileDialog1.FileName <> "" Then
FilePath=OpenFileDialog1.FileName
Dim xlapp = CreateObject ("Excel.Application")
Dim xlbook as object
Dim xlsheet As Excel.Worksheet
xlbook=xlapp.Workbooks.Open(FilePath)
xlsheet = CType(xlbook.Worksheets(1), Excel.Worksheet)
customername(1) = xlsheet.cells(3, 2)
customeraddress(1) = xlsheet.cells(3, 3)
customerphone(1) = xlsheet.cells(3, 4)
xlsheet = Nothing
xlbook.close(False)
xlbook = Nothing
xlapp=Nothin
End if

Marraco
March 14th, 2008, 12:26 PM
(don't forget to add the reference)

try:
With OpenFileDialog1
.Filter = "XLS files (*.xls)|*.xls|All files (*.*)|*.*"
.FilterIndex = 1
.Title = "Open Template"
.ShowDialog() '<-first mistake
End With
If OpenFileDialog1.FileName <> "" Then
FilePath = OpenFileDialog1.FileName
Dim xlapp = CType(CreateObject("Excel.Application"), Excel.Application)
Dim xlbook As Excel.Workbook '<-Better for writting code
Dim xlsheet As Excel.Worksheet
xlbook = xlapp.Workbooks.Open(FilePath)
xlsheet = CType(xlbook.Worksheets(1), Excel.Worksheet)
customername(1) = xlsheet.Cells(3, 2).value '<-explicit.value
customeraddress(1) = xlsheet.Cells(3, 3).value
customerphone(1) = xlsheet.Cells(3, 4).value
xlsheet = Nothing
xlbook.close(False)
xlbook = Nothing
xlapp = Nothing
End If