Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Basic 6
By Robert Karr, eHow Contributor
X
Share
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.
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
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.
Title
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."
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
Run your program and click on "Button1" to import "Sheet1" of your Excel spreadsheet to "Sheet1"
table in Access.
End Sub
Home
Search
What's
New
Index
Books
Links
Q&A
Newsletter
Banners
Title
Keywor
ADO, Access, Excel, database
ds
Categor
Database, Office
ies
Feedback
Tip Jar
C#
Helper...
MSDN Visual
Basic Community
max_row = excel_sheet.UsedRange.Rows.Count
max_col = excel_sheet.UsedRange.Columns.Count
","
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
waanders
1,464102658
add
comme
nt
3 Answers
activeoldest votes
up
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
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
vote
wn vote
Share
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!
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")
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
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
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
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
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
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.
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
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...
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.
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