25 July 2011

VB6: Export to Excel

Ada kalanya kita membutuhkan proses membuat dan mengisi file excel. Atau bisa jadi kita perlu melakukan export data ke excel.
Berikut ini adalah contoh code untuk eksport dari VB6 ke Excel.

UI:


Code:
Option Explicit

Private Sub Command1_Click()
'Deklarasi Object
Dim ApExcel As Object

'Set sebagai excel  object
Set ApExcel = CreateObject("Excel.application")

'Menyembunyikan proses excel
ApExcel.Visible = False


'Membuat/menambah workbook baru
ApExcel.Workbooks.Add

'Lebar Kolom
ApExcel.Columns(1).ColumnWidth = 3
ApExcel.Columns(2).ColumnWidth = 12
ApExcel.Columns(3).ColumnWidth = 9

'Mengisi Konten
ApExcel.Cells(1, 1).Value = "No"
ApExcel.Cells(1, 2).Value = "Nama"
ApExcel.Cells(1, 3).Value = "Kota"
'------------------------------------------
ApExcel.Cells(2, 1).Value = "1"
ApExcel.Cells(2, 2).Value = "Andra Dwiguna"
ApExcel.Cells(2, 3).Value = "Bandung"
'------------------------------------------
ApExcel.Cells(3, 1).Value = "2"
ApExcel.Cells(3, 2).Value = "Bonita Ariana"
ApExcel.Cells(3, 3).Value = "Jakarta"
'------------------------------------------
ApExcel.Cells(4, 1).Value = "3"
ApExcel.Cells(4, 2).Value = "Chairunisa Permata Dewi"
ApExcel.Cells(4, 3).Value = "Surabaya"

'Membuat Font Bold
ApExcel.Range("A1:C1").Font.Bold = True

'Memberi warna backgound
ApExcel.Range("A1:C1").interior.colorindex = 36

'Agar nilai cell yang panjang menjadi beberapa baris
ApExcel.Range("A2:C4").WrapText = True

'Membuat border hitam
ApExcel.Range("A1:C4").Borders.Color = RGB(0, 0, 0)

'Merge Cells

ApExcel.Range("A6:C7").Merge
ApExcel.Range("A8:C9").Merge
ApExcel.Range("A10:C11").Merge

'Input nilai ke merge cells
ApExcel.Cells(6, 1).Value = "SELAMAT MENCOBA!!!"
ApExcel.Cells(8, 1).Value = "Happy Coding Everyone :)"
ApExcel.Cells(10, 1).Value = "See You Again"

'Horizontal Align
ApExcel.Range("A6:C7").HorizontalAlignment = -4108 'xlCenter
ApExcel.Range("A8:C9").HorizontalAlignment = -4131 'xlLeft
ApExcel.Range("A10:C11").HorizontalAlignment = -4152 'xlRight
'Vertical Align
ApExcel.Range("A6:C7").VerticalAlignment = 1 'xlTop
ApExcel.Range("A8:C9").VerticalAlignment = 2 'xlCenter
ApExcel.Range("A10:C11").VerticalAlignment = 3 'xlBottom

'Warna Font
ApExcel.Range("A6:C7").Font.Color = RGB(255, 0, 0) 'Merah
ApExcel.Range("A8:C9").Font.Color = RGB(0, 255, 0) 'Hijau
ApExcel.Range("A10:C11").Font.Color = RGB(0, 0, 255) 'Biru

ApExcel.Visible = True

Set ApExcel = Nothing
End Sub


Runtime:

Click here if you like this article.


Baca Juga:
VB6: Menampilkan Data dari Excel ke Datagrid

0 comments: