Write data to Excel file using VB6

Visual Basic Topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Write data to Excel file using VB6

Post by Neo » Tue Apr 05, 2011 3:04 pm

Here is the code to write some data to an Excel file. We open a new Excel file first and then add data as we want. There are two methods to add data.
1. ws.Range("A1").Value
2. ws.Cells(x,y)

Another important thing is you need to add Microsoft Excel 12.0 Object Library from References.

Here is the code. This created a file named mytest.xls under C:\.

Code: Select all

Private Sub Command1_Click()

    Dim xlApp As Excel.Application
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim var As Variant
    
    Set xlApp = New Excel.Application
    
    Set wb = xlApp.Workbooks.Add ' Create a new WorkBook
    
    Set ws = wb.Worksheets("Sheet1") 'Specify your worksheet name
    
    wb.BuiltinDocumentProperties("Author").Value = "Neo" 'Author
    wb.BuiltinDocumentProperties("Company").Value = "ROBOT.LK" 'Company
    
    
    ' Two techniques to set values
    ws.Range("A1").Value = "ROBOT"
    ws.Cells(1, 2).Value = "LK"
    
    
    wb.SaveAs ("c:\mytest.xls")
    
    wb.Close
    
    xlApp.Quit
    
    Set ws = Nothing
    Set wb = Nothing
    Set xlApp = Nothing

End Sub
Post Reply

Return to “Visual Basic Programming”