How to Access Excel Spreadsheets With Visual Basic 6

29
How to Access Excel Spreadsheets With Visual Basic 6 By Robert Karr, eHow Contributor X Share Print this article How to Access Excel Spreadsheets With Visual Basic 6 Creating, accessing and adding or deleting data in Excel is all possible through Visual Basic 6. Some brief lines of code in Visual Basic will accomplish the first two actions. However, changing Excel data is more complicated and requires considerably more explanation than possible in this article. Writing programs to do this can be helpful if the developer needs to simplify the use of Excel for untrained users. Using Visual Basic forms allow for more modification and instruction than might be possible in Excel. Have a question? Get an answer from Online Tech Support now! Other People Are Reading How to Write Code in Microsoft Visual Basic Through Excel

description

pfizerCompetitive AdvantageCompetitive Advantage is the condition that enables a company to operate in a more efficient or in a higher-quality manner than the companies that it competes with, which results in benefits to that specific company. This is usually achieved by offering consumers greater value, either by means of lower prices or by providing greater benefits and services that justify for higher prices.One of the key strategies in achieving a competitive advantage is product differentiation. Product differentiation is the idea that certain features make one product appear different from competing products in the same market. Pfizer achieves this strategy through brand loyalty and advertising. Pfizer is a very well respected company; which makes them strongly trusted amongst their consumers. The way Pfizer achieves this trust is through their advertising and brand loyalty. Advertising and brand loyalty are very important in the pharmaceutical market due to the large interchangeability of its products. This basically means that there are a lot of products out there, in the Pharmaceutical industry, which are close substitutes to that of Pfizer’s and other companies. One way of avoiding such interchangeability is with the use of patents. A patent grants sole rights of a particular product to a specific company, making it illegal for other companies to make similar substitutable products. (www.pfizer.com)On the other hand Pfizer also competes with firms when there are no patents on their products. This is where Pfizer’s prestigious brand name and loyalty come into play. As earlier mentioned, many consumers trust Pfizer and its products to have a higher quality than any other pharmaceutical company. So when they need to purchase these products they look for the brand they can trust, Pfizer! The reason Pfizer is such a well-trusted company again comes from their advertising. Pfizer prides itself on its advertising ...

Transcript of How to Access Excel Spreadsheets With Visual Basic 6

Page 1: How to Access Excel Spreadsheets With Visual Basic 6

How to Access Excel Spreadsheets With Visual Basic 6By Robert Karr, eHow Contributor

X

Share Print this article

How to Access Excel Spreadsheets With Visual Basic 6

Creating, accessing and adding or deleting data in Excel is all possible through Visual Basic 6. Some brief lines of code in Visual Basic will accomplish the first two actions. However, changing Excel data is more complicated and requires considerably more explanation than possible in this article. Writing programs to do this can be helpful if the developer needs to simplify the use of Excel for untrained users. Using Visual Basic forms allow for more modification and instruction than might be possible in Excel. Have a question? Get an answer from Online Tech Support now!

Other People Are Reading

How to Write Code in Microsoft Visual Basic Through Excel

How to Save Excel Files in Visual Basic 6

Instructions

Page 2: How to Access Excel Spreadsheets With Visual Basic 6

1.

o 1

Open the Microsoft Visual Basic 6 program; click “File” and “New Project.” Choose “Standard.EXE” from the list of templates. A new form will open on the screen, labeled “Project 1 – Form1(Form)." Double-click three times on the Command Button icon in the left panel to add three buttons to the form. Save the form with a file name of your choice.

o 2

Click on “View” and “Properties Pages” (this may already be showing in the right-hand panel), and click on the first button on the form. In the Properties window, double-click “Caption” and change the text to “Open Existing Worksheet.” Change the second button caption to “Create New Worksheet.” Repeat for the third button, but change this caption to “Exit.” Drag the first two buttons so they are opposite each other. Place the third one below the other two.

o Sponsored Links Mobogenie: Free Download

Android SmartPhone PC Manager. 1-Click Download! (Windows Only)

www.mobogenie.com/Free_Apps

o 3

Double-click on the “Open Existing Spreadsheet” button. This changes the view from “Object” to “Code” and inserts a new procedure. Type these lines exactly as they appear between the "Private Sub Command1_Click()" and "End Sub," which should already be there.

Option ExplicitDim MyExcel As New Excel.ApplicationDim MyWorkbook As Excel.WorkbookDim MyWorksheet As Excel.WorksheetDim FileName As StringFileName = InputBox("Enter full name and location of Excel file")Set MyWorkbook = MyExcel.Workbooks.Open(FileName)Set MyWorksheet = MyExcel.ActiveSheetMyExcel.Visible = True

o 4

Page 3: How to Access Excel Spreadsheets With Visual Basic 6

Double-click on the “Create New Worksheet” and type these lines of code.

Set MyWorkbook = MyExcel.Workbooks.AddSet MyWorksheet = MyWorkbook.Worksheets("Sheet1")Set MyWorksheet = MyExcel.ActiveSheetMyExcel.Visible = True

o 5

Finish the code by double-clicking on the “Exit” button on the form and type these lines.

MyExcel.QuitEnd

o 6

Test the program by pressing “F5.” If it does not work, go back and double-check the code. It must be exact. If you get an error saying the existing file cannot be found, check the location and ensure you entered it exactly. When everything is working, click on “File,” then “Make” and follow it by the name you assigned to the project at the start. This will create an executable version you can run directly.

Read more: http://www.ehow.com/how_5895699_access-spreadsheets-visual-basic-6.html#ixzz2mlOqDsHc

eplace this "c:\temp\filename.xls" with your excel filename.

Private Sub ImportXLSheets()

Dim WrksheetName As StringDim i As IntegerDim xl As ObjectSet xl = CreateObject("Excel.Application")

xl.Visible = Truexl.Workbooks.Open "c:\temp\filename.xls"

With xl.Visible = TrueWith .Workbooks(.Workbooks.Count)

Page 4: How to Access Excel Spreadsheets With Visual Basic 6

For i = 1 To .Worksheets.CountWrksheetName = .Worksheets(i).NAMEDoCmd.TransferSpreadsheet (acImport), acSpreadsheetTypeExcel97, WrksheetName, "c:\temp\filename.xls"Next iEnd With

End WithSet xl = Nothing

End Sub

Title Copy data from an Excel spreadsheet into an Access database

Keywords ADO, Access, Excel, database

Categories Database, Office

 Using Excel as a server, open the spreadsheet. Use this code to find the largest rows and columns used. max_row = excel_sheet.UsedRange.Rows.Count max_col = excel_sheet.UsedRange.Columns.Count

Use ADO to open the database.

For each row in the Excel spreadsheet, loop through the row's columns composing an SQL INSERT statement. Use the ADO Connection object to execute the statement and create the record. Private Sub cmdLoad_Click()Dim excel_app As ObjectDim excel_sheet As ObjectDim max_row As IntegerDim max_col As IntegerDim row As IntegerDim col As IntegerDim conn As ADODB.ConnectionDim statement As StringDim new_value As String

Screen.MousePointer = vbHourglass DoEvents

' Create the Excel application. Set excel_app = CreateObject("Excel.Application")

' Uncomment this line to make Excel visible.' excel_app.Visible = True

' Open the Excel spreadsheet. excel_app.Workbooks.Open FileName:=txtExcelFile.Text

Page 5: How to Access Excel Spreadsheets With Visual Basic 6

' Check for later versions. If Val(excel_app.Application.Version) >= 8 Then Set excel_sheet = excel_app.ActiveSheet Else Set excel_sheet = excel_app End If

' Get the last used row and column. max_row = excel_sheet.UsedRange.Rows.Count max_col = excel_sheet.UsedRange.Columns.Count

' Open the Access database. Set conn = New ADODB.Connection conn.ConnectionString = _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & txtAccessFile.Text & ";" & _ "Persist Security Info=False" conn.Open

' Loop through the Excel spreadsheet rows, ' skipping the first row which contains ' the column headers. For row = 2 To max_row ' Compose an INSERT statement. statement = "INSERT INTO Books VALUES (" For col = 1 To max_col If col > 1 Then statement = statement & "," new_value = Trim$(excel_sheet.Cells(row, _ col).Value) If IsNumeric(new_value) Then statement = statement & _ new_value Else statement = statement & _ "'" & _ new_value & _ "'" End If Next col statement = statement & ")"

' Execute the INSERT statement. conn.Execute statement, , adCmdText Next row

' Close the database. conn.Close Set conn = Nothing

' Comment the Close and Quit lines to keep ' Excel running so you can see it.

' Close the workbook saving changes. excel_app.ActiveWorkbook.Close True excel_app.Quit

Set excel_sheet = Nothing

Page 6: How to Access Excel Spreadsheets With Visual Basic 6

Set excel_app = Nothing

Screen.MousePointer = vbDefault MsgBox "Copied " & Format$(max_row - 1) & " values."End Sub

Instructions1.

o 1Start a new Visual Basic.NET project and add a "Button" to your form. Select the "Project" menu and click "<projectname> Properties." Select "References" and click "Add." Select "COM" and click "Microsoft Office 12.0 Object Library." Select "OK."

o 2Create a new Excel spreadsheet and add the following data:

Field1 Field2

Data Data2

Data Data2

Save it to "C:\" as "ExcelToImport.xls."

o

o 3Double-click "Button1" on your form to open "Form1.vb." Type the following under "Button1_Click" to create a sub call:

importAllData("C:\ExcelToImport.xls", "C:\AccessFile.mdb")

MessageBox.Show("The import is complete!")

o 4Type the following to create a new sub called "importAllData" that will create a new database file for importing:

Private Shared Sub importAllData(ByVal file_path As String, ByVal db_path As String)

Dim accessDB As Microsoft.Office.Interop.Access.Application

accessDB = New Microsoft.Office.Interop.Access.ApplicationClass()

accessDB.Visible = False

accessDB.NewCurrentDatabase(db_path, Microsoft.Office.Interop.Access.AcNewDatabaseFormat.acNewDatabaseFormatAccess2007)

accessDB.CloseCurrentDatabase()

accessDB.Quit(Microsoft.Office.Interop.Access.AcQuitOption.acQuitSaveAll)

accessDB = Nothing

Page 7: How to Access Excel Spreadsheets With Visual Basic 6

Dim conn As OleDb.OleDbConnection = MakeExcelConnection(file_path)

FillAccessDatabase(conn, db_path, file_path)

End Sub

o 5Type the following to create a new sub called "FillAccessDatabase":

Private Shared Sub FillAccessDatabase(ByVal conn, ByVal db_path, ByVal file_path)

conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & file_path & ";" & "Extended Properties=Excel 12.0;"

Dim connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(conn)

Dim _command As OleDb.OleDbCommand = New OleDb.OleDbCommand()

_command.Connection = connection

_command.CommandText = "SELECT * INTO [MS Access;Database=" & db_path & "].[Sheet1] FROM [Sheet1$]"

connection.Open()

_command.ExecuteNonQuery()

connection.Close()

End Sub

o 6Type the following to create a new function called "MakeExcelConnection":

Private Shared Function MakeExcelConnection(ByVal fileName As String) As OleDb.OleDbConnection

Dim conn As String

conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & fileName & ";" & "Extended Properties=Excel 12.0;"

Dim connection As OleDb.OleDbConnection = New OleDb.OleDbConnection(conn)

Return connection

End Function

o 7Run your program and click on "Button1" to import "Sheet1" of your Excel spreadsheet to "Sheet1" table in Access.

Add a reference to Microsft excel object library:

Option Explicit

Private Sub Command1_Click()   Dim xlApp As Excel.Application   Dim wb As Workbook   Dim ws As Worksheet   Dim var As Variant

Page 8: How to Access Excel Spreadsheets With Visual Basic 6

   Set xlApp = New Excel.Application

   Set wb = xlApp.Workbooks.Open("PATH TO YOUR EXCEL FILE")

   Set ws = wb.Worksheets("Sheet1") 'Specify your worksheet name   var = ws.Range("A1").Value

   'or   var = ws.Cells(1, 1).Value   wb.Close

   xlApp.Quit

   Set ws = Nothing   Set wb = Nothing   Set xlApp = Nothing

End Sub

 

HomeSearch 

What's NewIndexBooksLinks

Q & A Newsletter

Banners 

FeedbackTip Jar 

C# Helper... 

 

 

 

 Title

Copy data from an Excel spreadsheet into an Access database

Keywords ADO, Access, Excel, database

Categories Database, Office

 

Using Excel as a server, open the spreadsheet. Use this code to find the largest rows and columns used.

max_row = excel_sheet.UsedRange.Rows.Count max_col = excel_sheet.UsedRange.Columns.Count

Use ADO to open the database.

For each row in the Excel spreadsheet, loop through the row's columns composing an SQL INSERT statement. Use the ADO Connection object to execute the statement and create the record.

 

Private Sub cmdLoad_Click()Dim excel_app As ObjectDim excel_sheet As ObjectDim max_row As IntegerDim max_col As IntegerDim row As Integer

Page 9: How to Access Excel Spreadsheets With Visual Basic 6

 

MSDN Visual Basic Community 

 

 

 

 

 

 

Dim col As IntegerDim conn As ADODB.ConnectionDim statement As StringDim new_value As String

Screen.MousePointer = vbHourglass DoEvents

' Create the Excel application. Set excel_app = CreateObject("Excel.Application")

' Uncomment this line to make Excel visible.' excel_app.Visible = True

' Open the Excel spreadsheet. excel_app.Workbooks.Open FileName:=txtExcelFile.Text

' Check for later versions. If Val(excel_app.Application.Version) >= 8 Then Set excel_sheet = excel_app.ActiveSheet Else Set excel_sheet = excel_app End If

' Get the last used row and column. max_row = excel_sheet.UsedRange.Rows.Count max_col = excel_sheet.UsedRange.Columns.Count

' Open the Access database. Set conn = New ADODB.Connection conn.ConnectionString = _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & txtAccessFile.Text & ";" & _ "Persist Security Info=False" conn.Open

' Loop through the Excel spreadsheet rows, ' skipping the first row which contains ' the column headers. For row = 2 To max_row ' Compose an INSERT statement. statement = "INSERT INTO Books VALUES (" For col = 1 To max_col If col > 1 Then statement = statement & "," new_value = Trim$(excel_sheet.Cells(row, _ col).Value) If IsNumeric(new_value) Then statement = statement & _ new_value Else statement = statement & _ "'" & _ new_value & _ "'" End If

Page 10: How to Access Excel Spreadsheets With Visual Basic 6

Next col statement = statement & ")"

' Execute the INSERT statement. conn.Execute statement, , adCmdText Next row

' Close the database. conn.Close Set conn = Nothing

' Comment the Close and Quit lines to keep ' Excel running so you can see it.

' Close the workbook saving changes. excel_app.ActiveWorkbook.Close True excel_app.Quit

Set excel_sheet = Nothing Set excel_app = Nothing

Screen.MousePointer = vbDefault MsgBox "Copied " & Format$(max_row - 1) & " values."End Sub

What's the "best" way to read (just read) an Excel file from within an Access 2007 application. I only want to loop trough the rows and put the data into an Access table.

I don't want a manually import (Get External Data dialog) but by VBA. The user gets a Form with a Browse button and then points to a Excel file with a defined content/format. After that the VBA code reads the data and puts it into the Access database.

excel ms-access ms-access-2007 access-vba office-2007

share|improve this question edited May 9 '12 at 13:32 asked May 25 '10 at 14:20

waanders1,464102658

add comment

3 Answersactiveoldestvotes

up  You could try the DoCmd.TransferSpreadsheet method.

Page 11: How to Access Excel Spreadsheets With Visual Basic 6

vot

e5down voteaccepted

DoCmd.TransferSpreadsheet acImport, , "from_excel","C:\Access\demo.xls", TrueThat imports spreadsheet data into a table named from_excel, and assumes the first row of the spreadsheet contains field names. See Access help for TransferSpreadsheet or online here , for more details.share|improve this answer answered May 25 '10 at 15:26

HansUp45.2k51838

add comment

up 

vot

e2down vote

If you want to read the entire spreadsheet in, you can import an Excel spreadsheet directly into Access. See here  or here .You can also choose to link to the Excel spreadsheet instead of importing it. That way any changes to the Excel spreadsheet will be reflected in the linked table. However, you won't be able to make changes from within Access.

A third option is to write some VBA code within Access to open a recordset and read the spreadsheet in. See the answers from KeithG in this thread . You can do something like this to open the spreadsheet in VBA:Dim xl As Excel.ApplicationDim xlsht As Excel.WorksheetDim xlWrkBk As Excel.Workbook

Set xl = CreateObject("Excel.Application")Set xlWrkBk = GetObject("H:/ggg.xls")Set xlsht = xlWrkBk.Worksheets(1)share|improve this answer edited May 25 '10 at 14:35 answered May 25 '10 at 14:24

TLiebe6,3131820

  Thanks, excellent tuts, but I meant a option by VBA. I've extended the question, see above –  waanders May 25 '10 at 14:31

  See my edited post for some info on how to access the spreadsheet through VBA. –  TLiebe May 25 '10 at 14:37

 You can run the import in VBA with DoCmd.TransferSpreadsheet. This answer seems very incomplete without a mention of that, seems to me. –  David-W-Fenton May 25 '10 at 18:08

Page 12: How to Access Excel Spreadsheets With Visual Basic 6

 TLiebe > Thanks for the answer, but I a prefer the TransferSpreadsheet answer. Unfortunately I can just mark 1 answer as the accepted answer –  waanders May 27 '10 at 8:40

add comment

up 

vot

e0down vote

Try something like this:

Dim excelApp As Excel.ApplicationDim workbook As Excel.WorkbookDim worksheet As Excel.Worksheet

Set excelApp = CreateObject("Excel.application")Set workbook = excelApp.Open("C:\someFileName.xls")Set worksheet = workbook.Worksheets(1)And then loop through the rows and columns, pull the data from the cells, and insert it into the database. (You can use the worksheet.cells method.) Try searching on google for code samples.

How to Read an Excel Spreadsheet in Visual BasicBy Lysis, eHow Contributor

 

 

Share 

  

Print this articleExcel spreadsheets are popular files used to store finances and sales analytical data. Programmers can use these spreadsheets to automate process and import data to an application, manipulate the values, and display them for users. It's also useful to read data from a spreadsheet and export it to a larger database like Microsoft SQL Server. Using Visual Basic, it's possible to read Excel files with only a few steps. Have a question? Get an answer from Online Tech Support now! 

Other People Are Reading

How to Read Xls File Vb

How to Query From an Excel Spreadsheet Using Visual Basic

Instructions1.

o 1

Page 13: How to Access Excel Spreadsheets With Visual Basic 6

Define the variables and instantiate the class. Before using any of the spreadsheet class methods and properties, the class needs an assigned variable.Dim excelapp As Excel.ApplicationDim excelWb As Excel.WorkbookDim excelSheet As Excel.Worksheetexcelapp = CreateObject("Excel.Application")

o 2Open the Excel file and assign it to the workbook object.excelWb = excelapp.Workbooks.Open("c:\\myExcelfile.xls")excelWb.Visible = TrueexcelWb.Activate()

o

o 3Activate the spreadsheet. You must specify which worksheet to use since Excel can have several spreadsheets in one file.excelSheet = excelWb.ActiveSheet

o 4Assign the first cell to a variable. You can assign multiple cells to an array, but for this example, one cell is read and printed to the console.string cell1 = excelSheet.Cells(1, 1).Value

o 5Verify the data by printing it to the console.Console.WriteLine(cell1);

Add a reference to Microsft excel object library:

Option Explicit

Private Sub Command1_Click()   Dim xlApp As Excel.Application   Dim wb As Workbook   Dim ws As Worksheet   Dim var As Variant

   Set xlApp = New Excel.Application

   Set wb = xlApp.Workbooks.Open("PATH TO YOUR EXCEL FILE")

   Set ws = wb.Worksheets("Sheet1") 'Specify your worksheet name   var = ws.Range("A1").Value

   'or   var = ws.Cells(1, 1).Value

Page 14: How to Access Excel Spreadsheets With Visual Basic 6

   wb.Close

   xlApp.Quit

   Set ws = Nothing   Set wb = Nothing   Set xlApp = Nothing

End Sub

  #3 (permalink)  

 June 3rd, 2003, 09:26 PM

tobin0971 

Registered User

 

Join Date: Jun 2003

Location: , , USA.

Posts: 2

Thanks: 0

Thanked 0 Times in 0 Posts

sjp,

Here is code to write to a text file and an excel file. As far as the reading from an excel file I am at a loss. You will need to add the Microsoft Common Dialog Control 6.0 (SP3) reference to your project. 

As far as using the text file, I do have problems when users enter a comma in a field, it doesn't use text delimiters. It makes it difficult to parse the data when I receive it.

HTH,Tricia

Call txt(rstSendFile)Call excel(rstSentFile)

(SEND MODULE)

Page 15: How to Access Excel Spreadsheets With Visual Basic 6

Option ExplicitPublic rstSendFile As ADODB.RecordsetPublic objExcel As ObjectPublic objTemp As ObjectPublic rstSendInfo As ADODB.Recordset

Public Function txt(rstSendFile As ADODB.Recordset) As Boolean

Dim iTotalRecords As IntegerDim sFileToExport As StringDim iFileNum As IntegerDim msg As StringDim iIndx As IntegerDim iNumberOfFields As IntegerScreen.MousePointer = vbDefault

On Error Resume NextCreateSendFileIf rstSendFile.RecordCount = 0 Then Exit Function

With frmMain.CD1  .CancelError = True  .FileName = "Export" & gsCustomerNumber & ".txt"  .InitDir = App.Path  .DialogTitle = "Save Text File"  .Filter = "Export Files (*.txt)|*.txt"  .DefaultExt = "TXT"  .Flags = cdlOFNOverwritePrompt Or cdlOFNCreatePrompt  .ShowSaveEnd With

'--------------------------------'-- User cancels the operation --'--------------------------------If Err.Number = cdlCancel Then 'operation canceled   Screen.MousePointer = vbDefault   msg = "The export operation was canceled." & vbCrLf   iIndx = MsgBox(msg, vbOKOnly + vbInformation, "Text Export File")   txt = False   Exit FunctionElse    On Error GoTo ErrorHandlerEnd If'---------------------------------------'-- Let's save the data now. --'-- Get the name of the file to save. --'---------------------------------------Screen.MousePointer = vbHourglass

Page 16: How to Access Excel Spreadsheets With Visual Basic 6

iTotalRecords = 0sFileToExport = frmMain.CD1.FileNameiFileNum = FreeFile()Open sFileToExport For Output As #iFileNum ' Open file for output.

'-------------------------'-- Stream out the data --'-------------------------

iNumberOfFields = rstSendFile.Fields.Count - 1rstSendFile.MoveFirstDo Until rstSendFile.EOF  iTotalRecords = iTotalRecords + 1  For iIndx = 0 To iNumberOfFields    If (IsNull(rstSendFile.Fields(iIndx))) Then       Print #iFileNum, ","; 'simply a comma delimited string    Else       If iIndx = iNumberOfFields Then         Print #iFileNum, Trim$(CStr(rstSendFile.Fields(iIndx)));       Else         Print #iFileNum, Trim$(CStr(rstSendFile.Fields(iIndx))); ",";       End If    End If  Next  Print #iFileNum,  rstSendFile.MoveNext  DoEventsLoop

'----------------Close #iFileNumScreen.MousePointer = vbDefaultmsg = "Export File " & sFileToExport & vbCrLfmsg = msg & "successfully created." & vbCrLfmsg = msg & iTotalRecords & " records written to disk." & vbCrLfiIndx = MsgBox(msg, vbOKOnly + vbInformation, "Comma Delimited File")txt = True

Dim iResponse As IntegerIf MsgBox("Do you want to record these records as sent?", _                        vbYesNoCancel, gsDialogTitle) = vbYes ThenWith rstSendInfo    If .EOF Then        .MoveFirst        !FileSentDate = Now()        .Update    Else

Page 17: How to Access Excel Spreadsheets With Visual Basic 6

        !FileSentDate = Now()        .Update    End IfEnd WithEnd IfExit Function

ErrorHandler:    DisplayErrorMessage    txt = FalseEnd Function

Public Sub CreateSendFile()Set rstSendFile = New ADODB.RecordsetSet rstSendInfo = New ADODB.Recordset

rstSendFile.CursorLocation = adUseClientrstSendFile.CursorLocation = adUseClient

rstSendFile.Open "SELECT * FROM qrySendInfo", gcnDue, adOpenForwardOnly, adLockOptimistic, adCmdTextrstSendInfo.Open "select * FROM SendInfo", gcnDue, adOpenForwardOnly, adLockOptimistic, adCmdTextIf rstSendFile.RecordCount = 0 Then    MsgBox "There are no records to export.", vbOKOnly, gsDialogTitleElse    MsgBox rstSendFile.RecordCount & " records will be exported.", vbOKOnly, gsDialogTitleEnd IfEnd Sub

Public Sub excel(rstSendFile As ADODB.Recordset)

Dim iIndx As IntegerDim iRowIndex As IntegerDim iColIndex As IntegerDim iRecordCount As IntegerDim iFieldCount As IntegerDim sMessage As StringDim avRows As VariantDim excelVersion As Integer

On Error GoTo ErrHandlerCreateSendFileIf rstSendFile.RecordCount = 0 Then Exit Sub

'-- Read all of the records into our arrayavRows = rstSendFile.GetRows()

Page 18: How to Access Excel Spreadsheets With Visual Basic 6

'-- Determine how many fields and recordsiRecordCount = UBound(avRows, 2) + 1iFieldCount = UBound(avRows, 1) + 1

'-- Create reference variable for the spreadsheetSet objExcel = CreateObject("Excel.Application")objExcel.Visible = TrueobjExcel.Workbooks.Add

'-- We need this line to insure Excel remains visible if we switchSet objTemp = objExcel

excelVersion = Val(objExcel.Application.Version)If (excelVersion >= 8) Then Set objExcel = objExcel.ActiveSheetEnd If

'-- Place the names of the fields as column headers --iRowIndex = 1iColIndex = 1For iColIndex = 1 To iFieldCount  With objExcel.Cells(iRowIndex, iColIndex)     .Value = rstSendFile.Fields(iColIndex - 1).Name     With .Font       .Name = "Arial"       .Bold = True       .Size = 9     End With  End WithNext

'-- memory management --rstSendFile.CloseSet rstSendFile = Nothing

'-- Just add data --With objExcel  For iRowIndex = 2 To iRecordCount + 1   For iColIndex = 1 To iFieldCount    .Cells(iRowIndex, iColIndex).Value = avRows(iColIndex - 1, iRowIndex - 2)   Next  NextEnd With

objExcel.Cells(1, 1).CurrentRegion.EntireColumn.AutoFit

Dim iResponse As IntegerIf MsgBox("Do you want to record these records as sent?", _

Page 19: How to Access Excel Spreadsheets With Visual Basic 6

                        vbYesNoCancel, gsDialogTitle) = vbYes ThenWith rstSendInfo    If .EOF Then        .MoveFirst        !FileSentDate = Now()        .Update    Else        !FileSentDate = Now()        .Update    End IfEnd WithEnd IfExit Sub

Exit SubErrHandler:    If Err.Number = 429 Then        MsgBox "You cannot use this feature unless you have Microsoft Excel loaded."        Exit Sub    Else        DisplayErrorMessage        Exit Sub    End IfEnd Sub

You can open an excel spreadsheet with ado and treat each worksheet like an ado recordset

dim oconn as adodb.connectiondim ors as adodb.recordset'' this assumes that the first row contains headers'Set oConn = New ADODB.ConnectionoConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & sxlsfilename & ";" & "Extended Properties=""Excel 8.0;HDR=YES;"""'' the table name is the worksheet name'sTableName = "[sheet1$]"sTableName = "select * from " & sTableName''Get the recordset'Set oRS = New ADODB.RecordsetoRS.Open sTableName, oConn, adOpenStatic, adLockOptimisticnCols = oRS.Fields.Count

Reading Excel Fle and Storing Contents in access data base

Hi,

I am facing problem while storing contents from excel to access data base.

Page 20: How to Access Excel Spreadsheets With Visual Basic 6

1) Able to read Excel file and its contents

2) But values are not storing in access data base

Here is the code

Code:

Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click Dim v_assessee_name, v_assessee_pan, v_assesse_address, v_assesse_nature As String Dim destinationPath As String = "D:\Development\TaxMate\Sample\Tax Mate\Tax Mate\bin\Data\" Dim sourcePath As String = txtPath.Text Dim fileName As String = GetFileName(txtPath.Text) destinationPath = destinationPath + fileName

If txtPath.Text = "" Then MsgBox("Please Select a file to Upload", MsgBoxStyle.Information) cmdBrowse.Focus() ElseIf GetFileExtension(txtPath.Text) = "xls" Or GetFileExtension(txtPath.Text) = "xlsx" Then

If System.IO.File.Exists(sourcePath) = True Then System.IO.File.Copy(sourcePath, destinationPath) MsgBox("File Moved") End If

conn.ConnectionString = cnString xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Open(destinationPath) xlWorkSheet = xlWorkBook.Worksheets("Sheet1") range = xlWorkSheet.UsedRange

For Me.rCnt = 2 To range.Rows.Count

v_assessee_name = CType(range.Cells(rCnt, 1), Excel.Range).Value() v_assessee_pan = CType(range.Cells(rCnt, 2), Excel.Range).Value() v_assesse_address = CType(range.Cells(rCnt, 3), Excel.Range).Value() v_assesse_nature = CType(range.Cells(rCnt, 4), Excel.Range).Value() Try conn.Open() sql = " insert into TMATE_ASSESSEE_MSTR (ASSESSEE_NAME, PAN_NO, ADDRESS, NATURE_OF_BUSINESS) " & _ " values (@ASSESSEE_NAME,@PAN_NO,@ADDRESS,@NATURE_OF_BUSINESS)" cmd = New OleDbCommand(sql, conn) cmd.Parameters.AddWithValue("@ASSESSEE_NAME", IIf(Trim(v_assessee_name) = "", DBNull.Value, v_assessee_name)) cmd.Parameters.AddWithValue("@PAN_NO", IIf(Trim(v_assessee_pan) = "", DBNull.Value, v_assessee_pan)) cmd.Parameters.AddWithValue("@ADDRESS", IIf(Trim(v_assesse_address) = "", DBNull.Value, v_assesse_address)) cmd.Parameters.AddWithValue("@NATURE_OF_BUSINESS", IIf(Trim(v_assesse_nature) = "", DBNull.Value, v_assesse_nature)) cmd.ExecuteNonQuery() MsgBox(v_assessee_name) MsgBox(v_assessee_pan) MsgBox(v_assesse_address) MsgBox(v_assesse_nature) conn.Close() Catch ex As Exception xlWorkBook.Close() xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) MsgBox("In Catch ....while uploading information into TMATE_ASSESSEE_MSTR......" & ex.Message) conn.Close() End Try

Next xlWorkBook.Close()

Page 21: How to Access Excel Spreadsheets With Visual Basic 6

xlApp.Quit() releaseObject(xlApp) releaseObject(xlWorkBook) releaseObject(xlWorkSheet) Else MsgBox("Please Upload Excel File only", MsgBoxStyle.Information) txtPath.Text = "" cmdBrowse.Focus() End If End If conn.Close() End Sub

can u tell me where i am doing mistake?

My mdb file will be stored in this folder

D:\Development\TaxMate\Sample\Tax Mate\Tax Mate\bin\Data\

Thanks in Advance

That code is a bit messed up. First up, you should not be opening and closing the database connection inside the loop. You open it, do all the work, then close it. Likewise, you have code to close the Excel file inside your loop so how do you expect to read the rest of the file? This is a perfect example of what happens when you try to write code without a clear picture of what that code is supposed to do. If you have a clear algorithm first then you can check whether the code you write implements that algorithm.

I would also strongly suggest not calling ExecuteNonQuery for every record. It will be more efficient to populate a DataTable as you read the data and then use a data adapter to insert the whole lot in one go. Here's an algorithm you should follow:

1. Open Excel file.2. Create DataTable.3. Loop through Excel file, adding a row to the DataTable for each row.4. Close Excel file.5. Open database connection.6. Save data.7. Close database connection.

Those last three steps can be done with a single call to Update on a data adapter. For an example, follow the CodeBank link in my signature and check out my thread on Retrieving & Saving Data.

Also, your connection string is a bit dodgy. You really should be adding the source database directly to your project and then letting a copy be created in the output folder when you build. The path in your connection string then literally reads "|DataDirectory|\MyDatabase.mdb". That will work while testing and after deployment without change.

Accessing Excel From VB

Posted by Dax on July 24, 2001 5:31 AM

Assuming you're using early binding by setting a reference to the Excel object library you could use code like this to refer to a cell's value.

Sub ReferToExcel()Dim xlApp As Excel.ApplicationDim wb As Excel.WorkbookDim ws As Excel.WorksheetDim x As Long, y As Long

Set xlApp = New Excel.ApplicationSet wb = xlApp.Workbooks.Open("C:\Temp\Anybook.xls")Set ws = wb.Sheets("Sheet1")

Page 22: How to Access Excel Spreadsheets With Visual Basic 6

x = 5y = 10

'Now reference the cell in the 5th row, 10th columnMsgBox "Row 5, Col 5 value=" & ws.Cells(x, y).Valuewb.Close False

'Quit ExcelxlApp.QuitSet xlApp = NothingSet wb = NothingSet ws = NothingEnd Sub

The code below will open the spreadsheet.

Dim xl As Excel.ApplicationDim xlsht As Excel.WorksheetDim xlWrkBk As Excel.Workbook

Set xl = CreateObject("Excel.Application")Set xlWrkBk = GetObject("H:/ggg.xls")Set xlsht = xlWrkBk.Worksheets(1)

Sub Link_To_Excel() 'WillR - www.willr.info  (December 2004) 'Macro Loops through the specified directory (strPath) 'and links ALL Excel files as linked tables in the Access 'Database. Const strPath As String = "serverpath\New Files for upload\" 'Directory Path Dim strFile As String 'Filename Dim strFileList() As String 'File Array Dim intFile As Integer 'File Number 'Dim intLine As Double 'Number of Lines 'Loop through the folder & build file list strFile = Dir(strPath & "*.xlsx") While strFile <> "" 'add files to the list intFile = intFile + 1 ReDim Preserve strFileList(1 To intFile) strFileList(intFile) = strFile strFile = Dir() Wend 'see if any files were found If intFile = 0 Then MsgBox "No files found" Exit Sub End If 'cycle through the list of files & import to Access 'appending to tables called DealerLists and DealerContacts For intFile = 1 To UBound(strFileList) 'Read the number of lines in the file Dim xl As Excel.Application Dim xlsht As Excel.worksheet Dim xlWrkBk As Excel.Workbook Dim xlCell As Double Set xl = CreateObject("Excel.Application") Set xlWrkBk = GetObject(strPath & strFileList(intFile))

Page 23: How to Access Excel Spreadsheets With Visual Basic 6

Set xlsht = xlWrkBk.Worksheets("Counters") Set xlCell = xlsht.cells(2, "A") DoCmd.TransferSpreadsheet acImport, , _ "DealerLists", strPath & strFileList(intFile), True, "parts!A1:E" & xlCell DoCmd.TransferSpreadsheet acImport, , _ "DealerContacts", strPath & strFileList(intFile), True, "contact!A1:F2" 'Check out the TransferSpreadsheet options in the Access 'Visual Basic Help file for a full description & list of optional settings Set xl = Nothing Set xlWrkBk = Nothing Set xlsht = Nothing Set xlCell = Nothing Next MsgBox UBound(strFileList)

& " Files were Imported"End Sub

Open EXCEL file with VB6 and read the content

imRahulSoni 

15 Dec 2006 8:04 AM 

18

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)

Page 24: How to Access Excel Spreadsheets With Visual Basic 6

    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

Page 25: How to Access Excel Spreadsheets With Visual Basic 6

    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