visual basic dapat membaca dan menulis informasi dari dan ke worksheet excel bahkan dapat...
DESCRIPTION
sTRANSCRIPT
Visual basic dapat membaca dan menulis informasi dari dan ke worksheet excel bahkan dapat melaksanakan perintah excel seperti merobah lebar column, memilih jenis huruf, mengatur border dll.
Untuk membuat koneksi Visual basic dengan excel dapat dilakukan dengan sangat mudah sehingga anda dengan mudah dapat menampilkan laporan keuangan dari aplikasi database visual basic ke dalam worksheet excel mulai dari form, laporan periodik, rugilaba, neraca bahkan grafik dll. Sebaliknya anda dapat mengimport data dari workseet excel ke database.
Berikut ini adalah cara membuat koneksi visual basic ke excel untuk membuka file tamplate yang telah disediakan dan selanjutnya anda dapat menuliskan informasi pada worksheet tersebut
Membuat koneksi
Dim vExcel As Excel.Application
Dim No, tbatal, tlunas, Tajt
No = 0
tbatal = 0
tlunas = 0
tajt = 0
Dim startRow
Membuka aplikasi Excel dengan mengalokasikan memori untuk aplikasi excel.
Set vExcel = CreateObject(“Excel.Application”)
Membuka file tamplate yang telah disediakan.
vExcel.Workbooks.Add (App.Path & “\namafile.xlt”)
Mengaktifkan Worksheet excel
vExcel.Visible = True
Menentukan windows excel ditampilkan maksimum
vExcel.WindowState = xlMaximized
Mengatur lebar Column misalnya column A akan di set menjadi 30
vExcel.Columns(“A”).ColumnWidth = 30
Menulis informasi ke dalam worksheet
With vExcel.ActiveSheet
.Cells(1, 1).Value = MyCom .Cells(2, 1).Value = MyAddr .Cells(3, 1).Value = “LAPORAN PENGELUARAN KAS” .Cells(4, 1).Value = “PERIODE : ” & Format(DrTgl, “dd-MMM”) & ” s/d ”
& Format(SdTgl, “dd-MMM-YYYY”) .Cells(6, 1).Value = “No” .Cells(6, 2).Value = “Voucher” .Cells(7, 2).Value = “Nomor” .Cells(7, 3).Value = “Tanggal” .Cells(6, 4).Value = “Chk/Giro” .Cells(7, 4).Value = “Nomor” .Cells(7, 5).Value = “Efektif” .Cells(6, 6).Value = “Rek” .Cells(6, 7).Value = “KodeSpl” .Cells(6, 8).Value = “Jumlah” .Cells(6, 9).Value = “Keterangan”
dan seterusnya …..
Dari cuplikan coding di atas anda telah mendapatkan header laporan pengeluaran kas yang selanjutnya anda tinggal mengisikan detail dari database yang telah tekoneksi melalui kodesi Ado dengan recordsed rs sbb
N = 1
startRow
Do While Not rs.EOF
‘Cells(Baris,Kolom)
.Cells(startRow + N, 1).Value = N
.Cells(startRow + N, 2).Value = rs!Voucher
.Cells(startRow + N, 3).Value = rs!tanggal
.Cells(startRow + N, 4).Value = rs!chkNo
.Cells(startRow + N, 5).Value = rs!efektif
.Cells(startRow + N, 6).Value = Left(rs!account, 6)
.Cells(startRow + N, 7).Value = rs!kodespl
.Cells(startRow + N, 8).Value = rs!Jumlah
.Cells(startRow + N, 9).Value = rs!Ket
‘ mendapatkan data yang telah jatuh tempo dan yang belum jatuh tempo
if rs!batal then
tbatal = tbatal + 1
else
If rs!efektif <= Date Then tlunas = tlunas + rs!Jumlah Else Tajt = Tajt + rs!Jumlah End If
End If rs.MoveNext N = N + 1 Loop
Using Excel with Visual Basic 6!
Hello Everyone! I would like to present this tutorial to you because I see some people asking questions about connecting to Excel, and manipulating Excel sheets in the forum.
My backgroundIn my work place, we use an Excel database. We have about 260 some excel files that hold all kinds of different data that is constantly being changed, and updated. Part of my job is to create tools that help manage this Excel database using Visual Basic 6. So I have acquired much knowledge about this subject through the countless number of tools I have created.
Lets begin!
I will be assuming that you have basic knowledge of programming, and Visual Basic 6 syntax. Such as variables, loops, conditional statements, arrays, ect.
The first thing you must do before writing code to manipulate Excel, is to add a reference to the Excel object library. Start up Visual Basic 6 and create a new Standard EXE project. Once you have your project, go to the Project drop down menu, and click References.
Project > References
Then in the list box, scroll down until you find "Microsoft Excel x Object Library" where x is the version. I have Microsoft Excel 12.0 Object Library. Once you find that check it and click OK.
Now that we are setup, we can start manipulating Excel with code.
Create Excel objects!
For this example, I will be writing code in the Form_Load() event.To create an Excel object you must declare an Excel variable:1 Dim excelApp As Excel.Application
After that, you must create the Excel object using the CreateObject() function.1 Set excelApp = CreateObject("Excel.Application")
Whooh! Now we have an excel object setup and ready to go! But we really can't do much with the object in this state that is visible to us. So to fix that, we will next create a workbook within the object.1 Set excelWB = excelApp.Workbooks.Add
Now we have a proper Excel application ready to do our bidding! If you set the visible property to true, and run the program, you will actually see an Excel application start up right before your eyes, without even having to press the little Excel shortcut icon! This is great stuff.
So this is what we have so far for the code.01 Private Sub Form_Load()
02
03 Dim excelApp As Excel.Application
04 Dim excelWB As Excel.Workbook
05
06 Set excelApp = CreateObject("Excel.Application")
07
08 Set excelWB = excelApp.Workbooks.Add
09
10 excelApp.Visible = True
11
12 End Sub
Adding data to a worksheet!
Now that you can actually see your creation, I'm sure you will want to manipulate it to carry
out your evil tasks So lets create a worksheet variable so we can start adding some data to it.
1 Dim excelWS As Excel.Worksheet
2 Set excelWS = excelWB.Worksheets(1)
There are a couple of ways to access the individual cells on a sheet, the ones I use are the Cells() and Range() members of the worksheet object. The Cells() member accepts two integer values as parameters which specify the column and row you want to access. I'm not very sure what the Range() member accepts as parameters, but you can pass it two strings which specify the cells, or two Cells() objects. I will give you an example of the usage of these two members.
01 'Examples of the Cells() member
02 excelWS.Cells(1, 1).Value = "Testing testing..."
03
04 For rowCounter = 2 To 1005 excelWS.Cells(rowCounter, 1).Value = "Using a loop to fill in cells"
06 Next rowCounter
07
08 'Examples of the Range() member09 excelWS.Range("A15", "F25").Value = "Using ranges with cell strings"
10
11 excelWS.Range(excelWS.Cells(1, 4), excelWS.Cells(10, 5)).Value = "Using ranges with Cells() objects"
Formatting!
So now that we can add data to a sheet, how about we make that data look pretty. Lets look at some font formatting first. For all your font manipulating needs, there is a member function called Font, which then has many member variables to setup fonts.
1 'Examples of font formatting
2 excelWS.Range("A15", "F25").Select3 With Selection.Font
4 .Size = 8
5 .Italic = True
6 .Bold = True
7 .Underline = True
8 .Name = "Arial Black"9 End With
Lets look at some number formatting and style now, such as increasing decimal length, and formatting for currency.
01 'Examples of number formating
02 excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 4)).Value = 50003 excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 2)).Select
04 With Selection
05 .NumberFormat = "$#,##0.00"
06 End With
07
08 excelWS.Range(excelWS.Cells(1, 3), excelWS.Cells(10, 3)).Select
09 With Selection
10 .NumberFormat = "#,##0.000"11 End With
12
13 excelWS.Range(excelWS.Cells(1, 4), excelWS.Cells(10, 4)).Select
14 With Selection
15 .Style = "Percent"
16 End With
Reading data from a worksheet!
Many times, I've needed to read in data from a worksheet in order to gather certain cells of data, and to perform calculations, ect. We will now save the workbook to your C: Drive, then reopen it in order to gather the data we put into it.
Lets first go over saving, and opening a workbook. You can find a list of file formats here: FileFormats
1 'Save and close
2 excelWB.SaveAs "C:\testing\testWB", FileFormat:=xlExcel83 excelWB.Close
To open a workbook, there is of course an Open() member function within the workbook member.1 Set excelWB = excelApp.Workbooks.Open("C:\testing\testWB.xls")
Except we are going to make it open on a button press. So on your main form, place a button somewhere. I didn't bother to rename my button so it will just be called Command1. Now double click the Command1 button to generate the click event code, or simply type it in manually.01 Private Sub Command1_Click()
02
03 Dim excelApp As Excel.Application
04 Dim excelWB As Excel.Workbook
05 Dim excelWS As Excel.Worksheet
06
07 Set excelApp = CreateObject("Excel.Application")
08
09 excelApp.Visible = True
10
11 Set excelWB = excelApp.Workbooks.Open("C:\testing\testWB.xls")
12
13 End Sub
I recoded the variables in the click event sub because the other variables not be in scope in this sub. I do it this way because I don't like using global variables. If you want to use global variables you can, just delete the variables and place them at the top of your code.
So now, we have code that will open the same workbook we were adding data to on a button click! Very cool huh?
So now lets read some of that data in. The first thing I will do is figure out how many rows, and columns the sheet has in it filled with data. This is a very useful thing to do when reading in data.
1 rowCount = excelWS.UsedRange.Rows.Count
2 colCount = excelWS.UsedRange.Columns.Count
Now that we know the range of our data, lets check to see if we can find a certain piece of data. There is a few ways to do this, so I'll show you a couple.01 ' One way to search for things
02 For r = 1 To rowCount
03 For c = 1 To colCount
04 If excelWS.Cells(r, c).Value = "Using ranges with cell strings" Then
05 ' Store the row number, and column number in a variable
06 foundRow = r
07 foundCol = c
08 excelWS.Cells(r, c).Value = "I found you!"09 End If
10 Next c
11 Next r
12
13 ' Another way
14 myRange = excelWS.Range("A2", "A10")
15 Set foundRange = myRange.Find("Using a loop to fill in cells", , xlFormulas, xlWhole, xlByColumns)
16 If Not (foundRange Is Nothing) Then
17 'We found it
18 End If
Adding and deleting worksheets!
This will be the last thing I cover in this massive tutorial. This will be quick and easy as it only takes a few lines of code. Both adding and deleting worksheets is contained within the workbook function.
01 'Delete the unused worksheets
02 For Each sheet In excelWB.Sheets03 If Not sheet.Name = "Sheet1" Then
04 sheet.Delete
05 End If06 Next sheet
07
08 ' Add a worksheet, then rename it
09 excelWB.Worksheets.Add
10 excelWB.Worksheets(1).Name = "NewlyCreated"
11
12 excelWB.Worksheets(1).Cells(1, 1).Value = "I'm new!"
Well, this concludes this tutorial. There is so much more functionality to working with Excel than I gave here. But this should be a good starting point for anyone seeking the knowledge. I hope everyone enjoys.
Fib
Full code:001 Private Sub Command1_Click()
002
003 Dim excelApp As Excel.Application
004 Dim excelWB As Excel.Workbook
005 Dim excelWS As Excel.Worksheet
006 Dim rowCount As Integer
007 Dim colCount As Integer
008 Dim r As Integer
009 Dim c As Integer
010 Dim foundRow As Integer011 Dim foundCol As Integer012 Dim foundRange As Range
013 Dim myRange As Range
014 Dim sheet As Worksheet
015
016 Set excelApp = CreateObject("Excel.Application")
017
018 excelApp.Visible = True
019
020 Set excelWB = excelApp.Workbooks.Open("C:\testing\testWB.xls")021 Set excelWS = excelWB.Worksheets(1)
022
023 rowCount = excelWS.UsedRange.Rows.Count
024 colCount = excelWS.UsedRange.Columns.Count
025
026 ' One way to search for things
027 For r = 1 To rowCount
028 For c = 1 To colCount
029 If excelWS.Cells(r, c).Value = "Using ranges with cell strings" Then
030 ' Store the row number, and column number in a variable
031 foundRow = r032 foundCol = c033 excelWS.Cells(r, c).Value = "I found you!"
034 End If
035 Next c
036 Next r
037
038 ' Another way
039 Set myRange = excelWS.Range("A2", "A10")
040 Set foundRange = myRange.Find("Using a loop to fill in cells", , xlFormulas, xlWhole, xlByColumns)
041 If Not (foundRange Is Nothing) Then
042 'We found it
043 End If
044
045 'Delete the unused worksheets
046 For Each sheet In excelWB.Sheets047 If Not sheet.Name = "Sheet1" Then
048 sheet.Delete
049 End If050 Next sheet
051
052 ' Add a worksheet, then rename it053 Set sheet = excelWB.Worksheets.Add
054 sheet.Name = "NewlyCreated"
055
056 sheet.Cells(1, 1).Value = "I'm new!"
057
058 End Sub
059
060 Private Sub Form_Load()
061
062 Dim excelApp As Excel.Application
063 Dim excelWB As Excel.Workbook
064 Dim excelWS As Excel.Worksheet065 Dim rowCounter As Integer
066
067 Set excelApp = CreateObject("Excel.Application")
068
069 excelApp.Visible = True
070 excelApp.DisplayAlerts = False
071
072 Set excelWB = excelApp.Workbooks.Add073 Set excelWS = excelWB.Worksheets(1)
074
075 'Examples of the Cells() member
076 excelWS.Cells(1, 1).Value = "Testing testing..."
077
078 For rowCounter = 2 To 10
079 excelWS.Cells(rowCounter, 1).Value = "Using a loop to fill in cells"
080 Next rowCounter
081
082 'Examples of the Range() member083 excelWS.Range("A15", "F25").Value = "Using ranges with cell strings"
084
085 excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 4)).Value = "Using ranges with Cells() objects"
086
087 'Examples of font formatting
088 excelWS.Range("A15", "F25").Select089 With Selection.Font
090 .Size = 8
091 .Italic = True
092 .Bold = True
093 .Underline = True094 .Underline = True095 .Name = "Arial Black"
096 End With
097
098 'Examples of number formating099 excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 4)).Value = 500
100 excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 2)).Select
101 With Selection
102 .NumberFormat = "$#,##0.00"103 End With
104
105 excelWS.Range(excelWS.Cells(1, 3), excelWS.Cells(10, 3)).Select
106 With Selection
107 .NumberFormat = "#,##0.000"
108 End With
109
110 excelWS.Range(excelWS.Cells(1, 4), excelWS.Cells(10, 4)).Select
111 With Selection
112 .Style = "Percent"113 End With
114
115 'Save and close
116 excelWB.SaveAs "C:\testing\testWB", FileFormat:=xlExcel8117 excelWB.Close
118
119 Excel.Application.Quit
120 Set excelApp = Nothing
121
122 End Sub123 124 125 Private Sub Form_Terminate()
126
127 Dim f As Form
128
129 For Each f In Forms
130 If f.hWnd <> Me.hWnd Then
131 Unload f
132 Set f = Nothing133 End If
134 Next f
135
136 Unload Me
137
138 End Sub
Bagi anda para software developer baik itu yang menggunakan database seperti MS Access ataupun database RDBMS seperti MS SQL Server, Oracle, MySQL dll, tentu anda pernah menginginkan agar data anda bisa dieksport ke format MS Excell untuk tujuan lainnya seperti ingin mempercantik format tampilan, sebagai bahan pembuatan laporan dan lain sebagainya. Walaupun ada banyak tool yang tersedia di internet untuk melakukan hal ini, tetapi mungkin saja anda ingin mengintegrasikan kemampuan ini dalam aplikasi yang anda buat. Adapun versi Visual Basic yang saya gunakan adalah Visual Basic versi 6.0 dan microsoft office yang saya gunakan adalah Microsoft Office 2003 (MS Office 11).PersiapanAplikasi ini akan kita gunakan untuk mengeksport data dari database Microsoft Access. Buat sebuah folder baru di drive C dan beri nama "ToExcel". Kemudian kita akan membuat sebuah database Microsoft Access langkahnya sebagai berikut : Klik Start Menu | Program | Microsoft Office Access 2003. Setelah masuk ke IDE microsoft access, klik menu File | New. Di menubar sebelah kanan pilih "Blank Database". Kemudian sebuah kotak dialog "File New Database" akan muncul. Simpan file tersebut di folder "ToExcel" yang telah kita buat tadi dan beri nama sample.mdb.Buat sebuah tabel dengan struktur data seperti dibawah ini :NIK text(10),Nama text(50),Jabatan text(30). Simpan tabel tersebut dan beri nama Karyawan. Kemudian isi beberapa data kedalam table tersebut.Pembuatan AplikasiJalankan MS Visual Basic : klik Start Menu | Program | Microsoft Visual Basic 6.0 | Microsoft Visual Basic 6.0. Setelah masuk ke Visual Basic IDE, kita akan melihat window yang mempunyai tiga tab dengan title "New Project".
Pilih "Standard EXE", kemudian akan muncul Project1 – Form1. klik menu File | Save Project As untuk menyimpan project ini. Simpan Form dengan nama FtoExcel.frm dan dengan projectnya dengan nama ExcelExport.vbp.Agar visual basic dapat menggunakan library untuk microsoft excel, maka kita harus mengaktifkan Library microsoft excel ini dengan cara : klik menu Project | References. Ini akan memunculkan window "References – Project1". Di dalam window ini terdapat banyak object library yang bisa digunakan untuk visual basic IDE. Kemudian centang object library yang berlabel "Microsoft Excel 11.0 Object Library" atau library "Microsoft Excel 10.0 Object Library" untuk pengguna Microsoft Office 2000 dan "Microsoft Excel 12.0 Object Library" untuk pengguna Microsoft Office 2007.
Ini akan memberitahukan kepada visual basic bahwa kita akan menggunakan object library dari Microsoft Office Excel 11.0 atau versi microsoft office excel yang anda gunakan.Interface AplikasiSekarang kita mulai dengan interface. Tambahkan sebuah CommandButton, DataGrid, Adodc dan sebuah label. Set nilai property masing-masing komponen sesuai dengan gambar dibawah ini :
Sehingga tampilannya seperti gambar dibawah ini :
Setting Database PathDalam men-set ConnectionString pada komponen adodc kita menggunakan path relative sebagai berikut :"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sample.mdb;Persist Security Info=False" . tidak menggunakan path absolute sebagai berikut :"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ToExcel\sample.mdb;Persist Security Info=False". Cara pertama (dengan path relative) akan membuat aplikasi lebih fleksibel. Maksudnya, meskipun aplikasi ini dipindahkan ke folder lain asalkan databasenya (.mdb) juga ditempatkan di folder yang sama dengan aplikasi (.exe) tersebut, aplikasi ini tidak akan mengalami error dan tidak perlu merubah source code dari aplikasi tersebut.CodingKlik kanan pada DataGrid1 pilih Retrieve Fileds untuk memasukanfield-field dari tabel karyawan ke komponen DataGrid1 secara otomatis.Sehingga tampilannya akan seperti gambar dibawah ini :
Langkah selanjutnya adalah mengisikan kode program ke dalam masing-masing komponen.klik di sembarang tempat di pada komponen Form1 kemudian tekan tombol F7ini akan memunculkan "Code Window".Isikan beberapa baris kode program berikut pada bagian paling atas sebelum kode Private Sub Form_Load().
---Option ExplicitDim koneksi_ado As ADODB.ConnectionDim rskaryawan As ADODB.Recordset---Kode diatas mendeklarasikan variabel koneksi_ado sebagai adodb conection dan rskaryawan sebagai adodb recordset.
Dobel Klik Komponen Form1, kemudian ketik kode berikut :---Dim SQLStr As StringSet koneksi_ado = New ADODB.ConnectionSet rskaryawan = New ADODB.Recordsetkoneksi_ado.ConnectionString= & _"Provider=Microsoft.Jet.OLEDB.4.0; & _Password=;Data Source=" & App.Path & "\sample.mdb" & _";Persist Security Info=True"koneksi_ado.OpenAdodc1.Enabled = TrueSQLStr = "select * from karyawan order by nama"rskaryawan.Open SQLStr, koneksi_ado, adOpenDynamic, adLockOptimisticDataGrid1.RefreshLabel1.Caption = "Status :"---
Kode diatas akan dieksekusi pada event form_load sehingga kode diatas akan dieksekusi ketika sebuah aplikasi pertama dijalankan.Langkah selanjutnya, mengisikan kode program utama yang akan di picu oleh komponen CommandButton1. Dobel klik CommandButton1, kemudian ketik kode berikut :---Dim EXCELAPPKU As Excel.Application
Dim excelbookku As Excel.WorkbookDim excelsheetku As Excel.WorksheetDim baris, datake As IntegerLabel1.Caption = "Status : Prosesing Data...."Set EXCELAPPKU = New Excel.ApplicationSet excelbookku = EXCELAPPKU.Workbooks.AddWith EXCELAPPKU.StandardFontSize = "10"End WithEXCELAPPKU.Visible = TrueSet excelsheetku = excelbookku.Worksheets(1)excelsheetku.SelectRange("A1:C1").SelectSelection.MergeCells = TrueSelection.HorizontalAlignment = xlCenterActiveCell.FormulaR1C1 = UCase("Data Karyawan")Selection.Font.Bold = TrueSelection.Font.Name = "Verdana"With excelsheetku.Cells(2, 1).Value = "NIK".Cells(2, 2).Value = "Nama".Cells(2, 3).Value = "Jabatan"Label1.Caption = "Status : Prosesing Data..."baris = 3datake = 0If Not rskaryawan.BOF Thenrskaryawan.MoveFirstWhile Not rskaryawan.EOFLabel1.Caption = "Status : Exporting Data ke " & datakeLabel1.Refreshdatake = datake + 1.Cells(1, 5).Value = "Fetching data ke " & datake.Cells(baris, 1) = rskaryawan![NIK].Cells(baris, 2) = rskaryawan![nama].Cells(baris, 3) = rskaryawan![jabatan]baris = baris + 1rskaryawan.MoveNextWendEnd If.Cells(1, 5).ClearContents.Columns("A:A").EntireColumn.AutoFit.Columns("B:B").EntireColumn.AutoFit.Columns("C:C").EntireColumn.AutoFitEnd Withrskaryawan.CloseLabel1.Caption = "Status : Selesai."On Error GoTo 0Set excelsheetku = NothingSet excelbookku = Nothing
EXCELAPPKU.QuitMsgBox "Export data selesai", vbInformation, "Informasi"---
Sekarang anda pilih menu Run | Start untuk menjalankan aplikasi. Tekan tombol "Eksport" untuk melihat outputnya.Berikut ini gambar aplikasi pada saat runtime :
Bagi anda para software developer baik itu yang menggunakan database seperti MS Access ataupun database RDBMS seperti MS SQL Server, Oracle, MySQL dll, tentu anda pernah menginginkan agar data anda bisa dieksport ke format MS Excell untuk tujuan lainnya seperti ingin mempercantik format tampilan, sebagai bahan pembuatan laporan dan lain sebagainya. Walaupun ada banyak tool yang tersedia di internet untuk melakukan hal ini, tetapi mungkin saja anda ingin mengintegrasikan kemampuan ini dalam aplikasi yang anda buat. Adapun versi Visual Basic yang saya gunakan adalah Visual Basic versi 6.0 dan microsoft office yang saya gunakan adalah Microsoft Office 2003 (MS Office 11).Persiapan
Aplikasi ini akan kita gunakan untuk mengeksport data dari database Microsoft Access. Buat sebuah folder baru di drive C dan beri nama "ToExcel". Kemudian kita akan membuat sebuah database Microsoft Access langkahnya sebagai berikut : Klik Start Menu | Program | Microsoft Office Access 2003. Setelah masuk ke IDE microsoft access, klik menu File | New. Di menubar sebelah kanan pilih "Blank Database". Kemudian sebuah kotak dialog "File New Database" akan muncul. Simpan file tersebut di folder "ToExcel" yang telah kita buat tadi dan beri nama sample.mdb.Buat sebuah tabel dengan struktur data seperti dibawah ini :NIK text(10),Nama text(50),Jabatan text(30). Simpan tabel tersebut dan beri nama Karyawan. Kemudian isi beberapa data kedalam table tersebut.Pembuatan AplikasiJalankan MS Visual Basic : klik Start Menu | Program | Microsoft Visual Basic 6.0 | Microsoft Visual Basic 6.0. Setelah masuk ke Visual Basic IDE, kita akan melihat window yang mempunyai tiga tab dengan title "New Project".
Pilih "Standard EXE", kemudian akan muncul Project1 – Form1. klik menu File | Save Project As untuk menyimpan project ini. Simpan Form dengan nama FtoExcel.frm dan dengan projectnya dengan nama ExcelExport.vbp.Agar visual basic dapat menggunakan library untuk microsoft excel, maka kita harus mengaktifkan Library microsoft excel ini dengan cara : klik menu Project | References. Ini akan memunculkan window "References – Project1". Di dalam window ini terdapat banyak object library yang bisa digunakan untuk visual basic IDE. Kemudian centang object library yang berlabel "Microsoft Excel 11.0 Object Library" atau library "Microsoft Excel 10.0 Object Library" untuk pengguna Microsoft Office 2000 dan "Microsoft Excel 12.0 Object Library" untuk pengguna Microsoft Office 2007.
Ini akan memberitahukan kepada visual basic bahwa kita akan menggunakan object library dari Microsoft Office Excel 11.0 atau versi microsoft office excel yang anda gunakan.Interface AplikasiSekarang kita mulai dengan interface. Tambahkan sebuah CommandButton, DataGrid, Adodc dan sebuah label. Set nilai property masing-masing komponen sesuai dengan gambar dibawah ini :
Sehingga tampilannya seperti gambar dibawah ini :
Setting Database PathDalam men-set ConnectionString pada komponen adodc kita menggunakan path relative sebagai berikut :"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sample.mdb;Persist Security Info=False" . tidak menggunakan path absolute sebagai berikut :"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ToExcel\sample.mdb;Persist Security Info=False". Cara pertama (dengan path relative) akan membuat aplikasi lebih fleksibel. Maksudnya, meskipun aplikasi ini dipindahkan ke folder lain asalkan databasenya (.mdb) juga ditempatkan di folder yang sama dengan aplikasi (.exe) tersebut, aplikasi ini tidak akan mengalami error dan tidak perlu merubah source code dari aplikasi tersebut.CodingKlik kanan pada DataGrid1 pilih Retrieve Fileds untuk memasukanfield-field dari tabel karyawan ke komponen DataGrid1 secara otomatis.Sehingga tampilannya akan seperti gambar dibawah ini :
Langkah selanjutnya adalah mengisikan kode program ke dalam masing-masing komponen.klik di sembarang tempat di pada komponen Form1 kemudian tekan tombol F7ini akan memunculkan "Code Window".Isikan beberapa baris kode program berikut pada bagian paling atas sebelum kode Private Sub Form_Load().
---Option Explicit
Dim koneksi_ado As ADODB.ConnectionDim rskaryawan As ADODB.Recordset---Kode diatas mendeklarasikan variabel koneksi_ado sebagai adodb conection dan rskaryawan sebagai adodb recordset.
Dobel Klik Komponen Form1, kemudian ketik kode berikut :---Dim SQLStr As StringSet koneksi_ado = New ADODB.ConnectionSet rskaryawan = New ADODB.Recordsetkoneksi_ado.ConnectionString= & _"Provider=Microsoft.Jet.OLEDB.4.0; & _Password=;Data Source=" & App.Path & "\sample.mdb" & _";Persist Security Info=True"koneksi_ado.OpenAdodc1.Enabled = TrueSQLStr = "select * from karyawan order by nama"rskaryawan.Open SQLStr, koneksi_ado, adOpenDynamic, adLockOptimisticDataGrid1.RefreshLabel1.Caption = "Status :"---
Kode diatas akan dieksekusi pada event form_load sehingga kode diatas akan dieksekusi ketika sebuah aplikasi pertama dijalankan.Langkah selanjutnya, mengisikan kode program utama yang akan di picu oleh komponen CommandButton1. Dobel klik CommandButton1, kemudian ketik kode berikut :---Dim EXCELAPPKU As Excel.ApplicationDim excelbookku As Excel.WorkbookDim excelsheetku As Excel.WorksheetDim baris, datake As IntegerLabel1.Caption = "Status : Prosesing Data...."Set EXCELAPPKU = New Excel.ApplicationSet excelbookku = EXCELAPPKU.Workbooks.AddWith EXCELAPPKU.StandardFontSize = "10"End WithEXCELAPPKU.Visible = TrueSet excelsheetku = excelbookku.Worksheets(1)excelsheetku.SelectRange("A1:C1").SelectSelection.MergeCells = TrueSelection.HorizontalAlignment = xlCenterActiveCell.FormulaR1C1 = UCase("Data Karyawan")Selection.Font.Bold = TrueSelection.Font.Name = "Verdana"With excelsheetku.Cells(2, 1).Value = "NIK".Cells(2, 2).Value = "Nama"
.Cells(2, 3).Value = "Jabatan"Label1.Caption = "Status : Prosesing Data..."baris = 3datake = 0If Not rskaryawan.BOF Thenrskaryawan.MoveFirstWhile Not rskaryawan.EOFLabel1.Caption = "Status : Exporting Data ke " & datakeLabel1.Refreshdatake = datake + 1.Cells(1, 5).Value = "Fetching data ke " & datake.Cells(baris, 1) = rskaryawan![NIK].Cells(baris, 2) = rskaryawan![nama].Cells(baris, 3) = rskaryawan![jabatan]baris = baris + 1rskaryawan.MoveNextWendEnd If.Cells(1, 5).ClearContents.Columns("A:A").EntireColumn.AutoFit.Columns("B:B").EntireColumn.AutoFit.Columns("C:C").EntireColumn.AutoFitEnd Withrskaryawan.CloseLabel1.Caption = "Status : Selesai."On Error GoTo 0Set excelsheetku = NothingSet excelbookku = NothingEXCELAPPKU.QuitMsgBox "Export data selesai", vbInformation, "Informasi"---
Sekarang anda pilih menu Run | Start untuk menjalankan aplikasi. Tekan tombol "Eksport" untuk melihat outputnya.Berikut ini gambar aplikasi pada saat runtime :