|
-
March 14th, 2008, 11:35 AM
#1
Trying to read data from the cells of a pre-existing Excel file
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
-
March 14th, 2008, 12:26 PM
#2
Re: Trying to read data from the cells of a pre-existing Excel file
(don't forget to add the reference)
try:
Code:
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
Last edited by Marraco; March 14th, 2008 at 12:33 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|