Open EXCEL file with VB6 and read the content
I was planning to write an application today which simply opens an Excel file and read the Cell values into an array so that I could manipulate it accordingly. Since I don't have VS.NET installed on my home PC, I decided to do it with VB6 :o)
Here is the code...
Private Sub cmdOpenExcel_Click()
On Error GoTo ErrHandler
Dim xlsApp As Object
Dim xlsWB1 As Object
'Late binding to open an XLS file which is present on my local harddisk
Set xlsApp = CreateObject("Excel.Application")
xlsApp.Visible = True
Set xlsWB1 = xlsApp.Workbooks.Open(strFileName)
Exit Sub
ErrHandler:
MsgBox "There is a problem while opening the xls document. " & _
" Please ensure it is present!", vbCritical, "Error"
End Sub
Now, since I know that my Excel file (which I want to work with) has 15 columns and 200 rows, here is what I did to read all the content to an Array for further manipulation.
Private Sub cmdParse_Click()
On Error GoTo ErrHandler:
Dim xlsApp As Object
Dim xlsWB1 As Object
Dim xlsWS1 As Object
'Opening the file to parse now
Set xlsApp = CreateObject("Excel.Application")
xlsApp.Visible = False
Set xlsWB1 = xlsApp.Workbooks.Open(strFileName)
Set xlsWS1 = xlsWB1.Worksheets("Sheet1")
Dim col As Integer
Dim row As Integer
Dim str As String
str = ""
MaxRow = 200
MaxCol = 15
'Declaring an array so that we don't have to depend on the excel file anymore
ReDim CaseArray(MaxRow, MaxCol)
'Reading the Excel file and putting everything in Memory for faster manipulation
For row = 1 To MaxRow
For col = 1 To MaxCol
CaseArray(row, col) = xlsWS1.cells(row, col).Value
Next
Next
xlsWB1.Close
xlsApp.Quit
Set xlsApp = Nothing
Set xlsWB1 = Nothing
Set xlsWS1 = Nothing
Exit Sub
ErrHandler:
MsgBox "An unknown error occurred while Parsing the Excel. Sorry about that!!" , vbCritical, "Error"
End Sub
In my case, CaseArray was a 2 dimensional Array using which I used in the other modules to manipulate the data as per my requirements!
Hope that helps!
Cheers,
Rahul