[VB6][Excel] Write to excel file


Deskripsi
      Menulis data dari VB6 ke Excel

How To

Hirarki aplikasi excel berupa : EXCEL > BOOK > SHEET
jadi kita harus mendefinisikan ketiganya terlebih dahulu


 Private Sub Command1_Click()  
   Dim oexcel As Object  
   Dim obook As Object  
   Dim osheet As Object  
   Set oexcel = CreateObject("Excel.Application")  
   Set obook = oexcel.workbooks.Add  
   Set osheet = obook.worksheets(1)  
   'Create Header First  
   osheet.Range("A1").Value = "Test Column 1"  
   osheet.Range("B1").Value = "Test Column 2"  
   osheet.Range("C1").Value = "Test Column 3"  
   osheet.Range("D1").Value = "Test Column 4"  
   osheet.Range("E1").Value = "Test Column 5"  
  'Add data to cells of the first worksheet in the new workbook  
   osheet.Range("A2").Value = "Blah1"  
   osheet.Range("B2").Value = "Blah2"  
   osheet.Range("C2").Value = "Blah3"  
   osheet.Range("D2").Value = "Blah4"  
   osheet.Range("E2").Value = "Blah5"  
   On Error GoTo localerr  
    'Save the Workbook and Quit Excel  
    oexcel.DisplayAlerts = False  
    obook.SaveAs "D:\myfirst_extract.xlsx"  
    oexcel.Quit  
    MsgBox "Extract to Excel Complete, file save in :" & "D:\myfirst_extract.xlsx"  
   Exit Sub  
   localerr:  
   If Err.Number = 1004 Then MsgBox "Failure to write file because file in use, please close first!",  vbCritical, "ERROR"  
 End Sub  

Note:

     *extensi untuk menyimpan bisa diganti sesuai versi excel yang diinginkan.
     *jangan lupa untuk selalu close excel setelah write ( oexcel.quit )

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih