Anda di halaman 1dari 22

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 background In 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 04 05 06 07 08 09 10 11 12 End Sub excelApp.Visible = True Set excelWB = excelApp.Workbooks.Add Set excelApp = CreateObject("Excel.Application") Dim excelApp As Excel.Application Dim excelWB As Excel.Workbook

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 to it. So lets create a worksheet variable so we can start adding some data

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 10 05 excelWS.Cells(rowCounter, 1).Value = "Using a loop to fill in cells" 06 Next rowCounter 07 08 'Examples of the Range() member 09 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").Select 3 With Selection.Font 4 .Size = 8 5 6 7 8 .Italic = True .Bold = True .Underline = True .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 = 500 03 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:=xlExcel8 3 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 04 05 06 07 08 09 10 11 12 13 End Sub Set excelWB = excelApp.Workbooks.Open("C:\testing\testWB.xls") excelApp.Visible = True Set excelApp = CreateObject("Excel.Application") Dim excelApp As Excel.Application Dim excelWB As Excel.Workbook Dim excelWS As Excel.Worksheet

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 If excelWS.Cells(r, c).Value = "Using ranges with cell 04 strings" Then 05 06 07 08 09 10 11 12 ' Store the row number, and column number in a variable foundRow = r foundCol = c excelWS.Cells(r, c).Value = "I found you!" End If Next c Next r

13 14 15

' Another way myRange = excelWS.Range("A2", "A10")

Set foundRange = myRange.Find("Using a loop to fill in cells", , xlFormulas, xlWhole, xlByColumns) 16 If Not (foundRange Is Nothing) Then 17 18 'We found it 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.Sheets 03 04 05 06 07 08 09 10 11 12 excelWB.Worksheets(1).Cells(1, 1).Value = "I'm new!" ' Add a worksheet, then rename it excelWB.Worksheets.Add excelWB.Worksheets(1).Name = "NewlyCreated" If Not sheet.Name = "Sheet1" Then sheet.Delete End If Next sheet

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 004 005 006 007 008 009 010 011 012 013 Dim excelApp As Excel.Application Dim excelWB As Excel.Workbook Dim excelWS As Excel.Worksheet Dim rowCount As Integer Dim colCount As Integer Dim r As Integer Dim c As Integer Dim foundRow As Integer Dim foundCol As Integer Dim foundRange As Range Dim myRange As Range

014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029

Dim sheet As Worksheet Set excelApp = CreateObject("Excel.Application") excelApp.Visible = True Set excelWB = excelApp.Workbooks.Open("C:\testing\testWB.xls") Set excelWS = excelWB.Worksheets(1) rowCount = excelWS.UsedRange.Rows.Count colCount = excelWS.UsedRange.Columns.Count ' One way to search for things For r = 1 To rowCount For c = 1 To colCount

If excelWS.Cells(r, c).Value = "Using ranges with cell strings" Then 030 ' Store the row number, and column number in a variable 031 032 033 034 035 036 037 038 039 ' Another way Set myRange = excelWS.Range("A2", "A10") Set foundRange = myRange.Find("Using a loop to fill in cells", , 040 xlFormulas, xlWhole, xlByColumns) 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 sheet.Cells(1, 1).Value = "I'm new!" ' Add a worksheet, then rename it Set sheet = excelWB.Worksheets.Add sheet.Name = "NewlyCreated" 'Delete the unused worksheets For Each sheet In excelWB.Sheets If Not sheet.Name = "Sheet1" Then sheet.Delete End If Next sheet If Not (foundRange Is Nothing) Then 'We found it End If foundRow = r foundCol = c excelWS.Cells(r, c).Value = "I found you!" End If Next c Next r

057 058 End Sub 059 060 Private Sub Form_Load() 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 For rowCounter = 2 To 10 excelWS.Cells(rowCounter, 1).Value = "Using a loop to fill in cells" 080 Next rowCounter 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 'Examples of number formating 'Examples of font formatting excelWS.Range("A15", "F25").Select With Selection.Font .Size = 8 .Italic = True .Bold = True .Underline = True .Underline = True .Name = "Arial Black" End With excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 4)).Value = "Using ranges with Cells() objects" 'Examples of the Range() member excelWS.Range("A15", "F25").Value = "Using ranges with cell strings" 'Examples of the Cells() member excelWS.Cells(1, 1).Value = "Testing testing..." Set excelWB = excelApp.Workbooks.Add Set excelWS = excelWB.Worksheets(1) excelApp.Visible = True excelApp.DisplayAlerts = False Set excelApp = CreateObject("Excel.Application") Dim excelApp As Excel.Application Dim excelWB As Excel.Workbook Dim excelWS As Excel.Worksheet Dim rowCounter As Integer

099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 4)).Value = 500 excelWS.Range(excelWS.Cells(1, 2), excelWS.Cells(10, 2)).Select With Selection .NumberFormat = "$#,##0.00" End With excelWS.Range(excelWS.Cells(1, 3), excelWS.Cells(10, 3)).Select With Selection .NumberFormat = "#,##0.000" End With excelWS.Range(excelWS.Cells(1, 4), excelWS.Cells(10, 4)).Select With Selection .Style = "Percent" End With 'Save and close excelWB.SaveAs "C:\testing\testWB", FileFormat:=xlExcel8 excelWB.Close Excel.Application.Quit Set excelApp = Nothing

122 End Sub 123 124 125 Private Sub Form_Terminate() 126 127 128 129 130 131 132 133 134 135 136 137 138 End Sub Unload Me For Each f In Forms If f.hWnd <> Me.hWnd Then Unload f Set f = Nothing End If Next f Dim f As Form

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 Aplikasi Jalankan 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 Aplikasi Sekarang 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 Path Dalam 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. Coding Klik kanan pada DataGrid1 pilih Retrieve Fileds untuk memasukan field-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 F7 ini 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.Connection Dim 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 String Set koneksi_ado = New ADODB.Connection Set rskaryawan = New ADODB.Recordset koneksi_ado.ConnectionString= & _ "Provider=Microsoft.Jet.OLEDB.4.0; & _ Password=;Data Source=" & App.Path & "\sample.mdb" & _ ";Persist Security Info=True" koneksi_ado.Open Adodc1.Enabled = True SQLStr = "select * from karyawan order by nama" rskaryawan.Open SQLStr, koneksi_ado, adOpenDynamic, adLockOptimistic DataGrid1.Refresh Label1.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.Workbook Dim excelsheetku As Excel.Worksheet Dim baris, datake As Integer Label1.Caption = "Status : Prosesing Data...." Set EXCELAPPKU = New Excel.Application Set excelbookku = EXCELAPPKU.Workbooks.Add With EXCELAPPKU .StandardFontSize = "10" End With EXCELAPPKU.Visible = True Set excelsheetku = excelbookku.Worksheets(1) excelsheetku.Select Range("A1:C1").Select Selection.MergeCells = True Selection.HorizontalAlignment = xlCenter ActiveCell.FormulaR1C1 = UCase("Data Karyawan") Selection.Font.Bold = True Selection.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 = 3 datake = 0 If Not rskaryawan.BOF Then rskaryawan.MoveFirst While Not rskaryawan.EOF Label1.Caption = "Status : Exporting Data ke " & datake Label1.Refresh datake = 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 + 1 rskaryawan.MoveNext Wend End If .Cells(1, 5).ClearContents .Columns("A:A").EntireColumn.AutoFit .Columns("B:B").EntireColumn.AutoFit .Columns("C:C").EntireColumn.AutoFit End With rskaryawan.Close Label1.Caption = "Status : Selesai." On Error GoTo 0 Set excelsheetku = Nothing Set excelbookku = Nothing EXCELAPPKU.Quit MsgBox "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 Aplikasi Jalankan 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 Aplikasi Sekarang 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 Path Dalam 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. Coding Klik kanan pada DataGrid1 pilih Retrieve Fileds untuk memasukan field-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 F7 ini 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.Connection Dim 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 String Set koneksi_ado = New ADODB.Connection Set rskaryawan = New ADODB.Recordset koneksi_ado.ConnectionString= & _ "Provider=Microsoft.Jet.OLEDB.4.0; & _ Password=;Data Source=" & App.Path & "\sample.mdb" & _ ";Persist Security Info=True" koneksi_ado.Open Adodc1.Enabled = True SQLStr = "select * from karyawan order by nama" rskaryawan.Open SQLStr, koneksi_ado, adOpenDynamic, adLockOptimistic DataGrid1.Refresh Label1.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.Workbook Dim excelsheetku As Excel.Worksheet Dim baris, datake As Integer Label1.Caption = "Status : Prosesing Data...." Set EXCELAPPKU = New Excel.Application Set excelbookku = EXCELAPPKU.Workbooks.Add With EXCELAPPKU .StandardFontSize = "10" End With EXCELAPPKU.Visible = True Set excelsheetku = excelbookku.Worksheets(1) excelsheetku.Select Range("A1:C1").Select Selection.MergeCells = True Selection.HorizontalAlignment = xlCenter ActiveCell.FormulaR1C1 = UCase("Data Karyawan") Selection.Font.Bold = True Selection.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 = 3 datake = 0 If Not rskaryawan.BOF Then rskaryawan.MoveFirst While Not rskaryawan.EOF Label1.Caption = "Status : Exporting Data ke " & datake Label1.Refresh datake = 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 + 1 rskaryawan.MoveNext Wend End If .Cells(1, 5).ClearContents .Columns("A:A").EntireColumn.AutoFit .Columns("B:B").EntireColumn.AutoFit .Columns("C:C").EntireColumn.AutoFit End With rskaryawan.Close Label1.Caption = "Status : Selesai." On Error GoTo 0 Set excelsheetku = Nothing Set excelbookku = Nothing

EXCELAPPKU.Quit MsgBox "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 :

Anda mungkin juga menyukai