Sei sulla pagina 1di 25

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

How to Save Excel Files in Visual Basic 6

Instructions
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.

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.
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 Explicit
Dim MyExcel As New Excel.Application
Dim MyWorkbook As Excel.Workbook

Dim MyWorksheet As Excel.Worksheet


Dim FileName As String
FileName = InputBox("Enter full name and location of Excel file")
Set MyWorkbook = MyExcel.Workbooks.Open(FileName)
Set MyWorksheet = MyExcel.ActiveSheet
MyExcel.Visible = True
o

4
Double-click on the Create New Worksheet and type these lines of
code.
Set MyWorkbook = MyExcel.Workbooks.Add
Set MyWorksheet = MyWorkbook.Worksheets("Sheet1")
Set MyWorksheet = MyExcel.ActiveSheet
MyExcel.Visible = True

5
Finish the code by double-clicking on the Exit button on the form
and type these lines.
MyExcel.Quit
End

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-visualbasic-6.html#ixzz2mlOqDsHc

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


Private Sub ImportXLSheets()

Dim WrksheetName As String


Dim i As Integer
Dim xl As Object
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Open "c:\temp\filename.xls"
With xl
.Visible = True
With .Workbooks(.Workbooks.Count)
For i = 1 To .Worksheets.Count
WrksheetName = .Worksheets(i).NAME
DoCmd.TransferSpreadsheet (acImport), acSpreadsheetTypeExcel97, WrksheetName,
"c:\temp\filename.xls"
Next i
End With
End With
Set 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 Object
Dim excel_sheet As Object
Dim max_row As Integer
Dim max_col As Integer
Dim row As Integer
Dim col As Integer
Dim conn As ADODB.Connection

Dim statement As String


Dim 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
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

Instructions
1.

Start 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."

Create a new Excel spreadsheet and add the following data:


Field1 Field2
Data Data2
Data Data2
Save it to "C:\" as "ExcelToImport.xls."

o
o

Double-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

Type 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
Dim conn As OleDb.OleDbConnection = MakeExcelConnection(file_path)
FillAccessDatabase(conn, db_path, file_path)
End Sub

Type 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

Type 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

Run 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
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

Home
Search
What's
New
Index
Books
Links
Q&A
Newsletter
Banners

Title

Copy data from an Excel spreadsheet into an


Access database

Keywor
ADO, Access, Excel, database
ds
Categor
Database, Office
ies

Using Excel as a server, open the spreadsheet. Use this


code to find the largest rows and columns used.

Feedback
Tip Jar

C#
Helper...

MSDN Visual
Basic Community

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 Object
Dim excel_sheet As Object
Dim max_row As Integer
Dim max_col As Integer
Dim row As Integer
Dim col As Integer
Dim conn As ADODB.Connection
Dim statement As String
Dim 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
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

waanders
1,464102658
add
comme
nt

3 Answers
activeoldest votes

up

You could try the DoCmd.TransferSpreadsheet method.

5do DoCmd.TransferSpreadsheet acImport, , "from_excel","C:\Access\demo.xls", True

vote

wn vote

accept ed

That 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.
answered May 25 '10 at
share|improve this answer
15:26

HansUp
45.2k51838
add comment
up

If you want to read the entire spreadsheet in, you can import an Excel spreadsheet directly into Access.
See here or here .
vote do
You can also choose to link to the Excel spreadsheet instead of importing it. That way any changes to the
wn vote
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.Application
Dim xlsht As Excel.Worksheet
Dim 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

TLiebe
6,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
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

Try something like this:

0do Dim excelApp As Excel.Application

vote

wn vote

Dim workbook As Excel.Workbook


Dim 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


Basic
By Lysis, eHow Contributor

Share

Print this article

Excel 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

Instructions
1.

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.Application
Dim excelWb As Excel.Workbook
Dim excelSheet As Excel.Worksheet
excelapp = CreateObject("Excel.Application")

Open the Excel file and assign it to the workbook object.


excelWb = excelapp.Workbooks.Open("c:\\myExcelfile.xls")
excelWb.Visible = True
excelWb.Activate()

o
o

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

4
Assign 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

Verify 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
wb.Close
xlApp.Quit
Set ws = Nothing
Set wb = Nothing
Set xlApp = Nothing

End Sub

#3 (permalink)
June 3rd, 2003, 09:26 PM
Join Date: Jun 2003
Location: , , USA.

tobin0971
Registered User

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)
Option Explicit
Public rstSendFile As ADODB.Recordset
Public objExcel As Object
Public objTemp As Object
Public rstSendInfo As ADODB.Recordset
Public Function txt(rstSendFile As ADODB.Recordset) As Boolean
Dim iTotalRecords As Integer
Dim sFileToExport As String
Dim iFileNum As Integer
Dim msg As String
Dim iIndx As Integer
Dim iNumberOfFields As Integer
Screen.MousePointer = vbDefault
On Error Resume Next
CreateSendFile
If 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
.ShowSave

End 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 Function
Else
On Error GoTo ErrorHandler
End If
'--------------------------------------'-- Let's save the data now. -'-- Get the name of the file to save. -'--------------------------------------Screen.MousePointer = vbHourglass
iTotalRecords = 0
sFileToExport = frmMain.CD1.FileName
iFileNum = FreeFile()
Open sFileToExport For Output As #iFileNum ' Open file for output.
'------------------------'-- Stream out the data -'------------------------iNumberOfFields = rstSendFile.Fields.Count - 1
rstSendFile.MoveFirst
Do 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
DoEvents
Loop

'---------------Close #iFileNum
Screen.MousePointer = vbDefault
msg = "Export File " & sFileToExport & vbCrLf
msg = msg & "successfully created." & vbCrLf
msg = msg & iTotalRecords & " records written to disk." & vbCrLf
iIndx = MsgBox(msg, vbOKOnly + vbInformation, "Comma Delimited File")
txt = True
Dim iResponse As Integer
If MsgBox("Do you want to record these records as sent?", _
vbYesNoCancel, gsDialogTitle) = vbYes Then
With rstSendInfo
If .EOF Then
.MoveFirst
!FileSentDate = Now()
.Update
Else
!FileSentDate = Now()
.Update
End If
End With
End If
Exit Function
ErrorHandler:
DisplayErrorMessage
txt = False
End Function
Public Sub CreateSendFile()
Set rstSendFile = New ADODB.Recordset
Set rstSendInfo = New ADODB.Recordset
rstSendFile.CursorLocation = adUseClient
rstSendFile.CursorLocation = adUseClient
rstSendFile.Open "SELECT * FROM qrySendInfo", gcnDue, adOpenForwardOnly,
adLockOptimistic, adCmdText
rstSendInfo.Open "select * FROM SendInfo", gcnDue, adOpenForwardOnly, adLockOptimistic,
adCmdText
If rstSendFile.RecordCount = 0 Then
MsgBox "There are no records to export.", vbOKOnly, gsDialogTitle
Else
MsgBox rstSendFile.RecordCount & " records will be exported.", vbOKOnly, gsDialogTitle
End If
End Sub

Public Sub excel(rstSendFile As ADODB.Recordset)


Dim iIndx As Integer
Dim iRowIndex As Integer
Dim iColIndex As Integer
Dim iRecordCount As Integer
Dim iFieldCount As Integer
Dim sMessage As String
Dim avRows As Variant
Dim excelVersion As Integer
On Error GoTo ErrHandler
CreateSendFile
If rstSendFile.RecordCount = 0 Then Exit Sub
'-- Read all of the records into our array
avRows = rstSendFile.GetRows()
'-- Determine how many fields and records
iRecordCount = UBound(avRows, 2) + 1
iFieldCount = UBound(avRows, 1) + 1
'-- Create reference variable for the spreadsheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
'-- We need this line to insure Excel remains visible if we switch
Set objTemp = objExcel
excelVersion = Val(objExcel.Application.Version)
If (excelVersion >= 8) Then
Set objExcel = objExcel.ActiveSheet
End If
'-- Place the names of the fields as column headers -iRowIndex = 1
iColIndex = 1
For 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 With

Next
'-- memory management -rstSendFile.Close
Set 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
Next
End With
objExcel.Cells(1, 1).CurrentRegion.EntireColumn.AutoFit
Dim iResponse As Integer
If MsgBox("Do you want to record these records as sent?", _
vbYesNoCancel, gsDialogTitle) = vbYes Then
With rstSendInfo
If .EOF Then
.MoveFirst
!FileSentDate = Now()
.Update
Else
!FileSentDate = Now()
.Update
End If
End With
End If
Exit Sub
Exit Sub
ErrHandler:
If Err.Number = 429 Then
MsgBox "You cannot use this feature unless you have Microsoft Excel loaded."
Exit Sub
Else
DisplayErrorMessage
Exit Sub
End If
End Sub
You can open an excel spreadsheet with ado and treat each worksheet like an ado recordset
dim oconn as adodb.connection
dim ors as adodb.recordset
'
' this assumes that the first row contains headers

'
Set oConn = New ADODB.Connection
oConn.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.Recordset
oRS.Open sTableName, oConn, adOpenStatic, adLockOptimistic
nCols = 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.
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()
Else
If 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()
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.
2.
3.
4.

Open Excel file.


Create DataTable.
Loop through Excel file, adding a row to the DataTable for each row.
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.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim x As Long, y As Long
Set xlApp = New Excel.Application
Set wb = xlApp.Workbooks.Open("C:\Temp\Anybook.xls")
Set ws = wb.Sheets("Sheet1")
x=5
y = 10
'Now reference the cell in the 5th row, 10th column
MsgBox "Row 5, Col 5 value=" & ws.Cells(x, y).Value
wb.Close False
'Quit Excel
xlApp.Quit
Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing
End Sub

The code below will open the spreadsheet.

Dim xl As Excel.Application
Dim xlsht As Excel.Worksheet
Dim 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
Set
Set
Set

xl = CreateObject("Excel.Application")
xlWrkBk = GetObject(strPath & strFileList(intFile))
xlsht = xlWrkBk.Worksheets("Counters")
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)
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

Potrebbero piacerti anche