Recent Posts

Tuesday, March 11, 2008

Read Excel File from VB 6.0

This article provides full details on how to retrieve the Excel data in Visual Basic 6.0 application. Just use the code provided in this article and it should work for you. Also there are various comments in the code that helps to understand the code by beginners as well.

See below for the code to retrieve the excel data:

Private Sub LoadExcel(ByVal strSheet As String)

On Error GoTo EErr

'This can be done to directly access excel but you need to add reference for excel

'Dim objExcel As Excel.Application
'Dim objSpread As Excel.Workbook

Dim introw As Integer

Dim strSNo As String
Dim strEntryNo As String
Dim strFName As String
Dim strMName As String
Dim strLName As String
Dim strFather As String

Dim objExcel As Object
Dim objSpread As Object
Dim introw As Integer

' Open the Excel spreadsheet
Set objExcel = CreateObject("Excel.Application")
Set objSpread = objExcel.Workbooks.Open(strSheet)

' This is done to avoid unnecessary running excel.exe application in memory
' This closes the excel once it is set to nothing after the work is done
objExcel.UserControl = True

'Decide the row from which you want to start reading the excel
introw = 1
' Now reading the excel file row by row after opening the excel File

Do Until objExcel.Rows.Count = 113

strEntryNo = Trim(objExcel.Cells(introw, 2).Value)
strFName = Trim(objExcel.Cells(introw, 3).Value)
strMName = Trim(objExcel.Cells(introw, 4).Value)
strLName = Trim(objExcel.Cells(introw, 5).Value)
strFather = Trim(objExcel.Cells(introw, 6).Value)
introw = introw + 1
Loop

' This is essential to close the excel file
objExcel.Quit
Set objSpread = Nothing
Set objExcel = Nothing

Exit Sub
EErr:
' This is essential to close the excel file
objExcel.Quit
Set objSpread = Nothing
Set objExcel = Nothing
Err.Raise Err.Number, Err.Source, Err.Description

End Sub

Related Posts by Categories




2 comments:

Anonymous said...

How do I read the combobox.text value within the excel sheet into vb ?

rprateek said...

I have been working in C# and haven't worked in excel or vb6 lately, I can't go through it now.

But I think you have to get the value from the other sheet where you load up the combo box.

Post a Comment