Excel VBA - UsingVBA to create a new, formatted workbook

后端 未结 4 1713
耶瑟儿~
耶瑟儿~ 2021-01-25 06:52

I\'m trying to write the last part of my program and I need to pull data from an Access document and print it into a new Workbook.

To start, I will be taking the names o

4条回答
  •  清歌不尽
    2021-01-25 07:33

    As my previous answer was deleted (considered "insuficient"), I have to provide a better one.

    If you want to output data from Access to Excel, you have to follow this steps:

    1. Create (or open) a new workbook
    2. Read your data
    3. Write your data to the workbook
    4. Format the data in the workbook

    I will focus on the data output, and leave the formatting out (the data part is the complicated one... formatting is easy)

    First, you need to enable the Excel objects in your Access file: Tools Menu > References. Find the Microsoft Excel 12.0 Object Library and activate the checkbox. Now you have the full Excel library at your service :-)

    Now is the time for the data crunching. I will asume that you need to create a new workbook:

    public sub createExcelFile()
        dim XL as Excel.Application, WB as Excel.Workbook, WKS as Excel.Worksheet
        dim db as DAO.database, rec as DAO.recordset, f as DAO.field
        dim i as integer, j as integer
    
        ' Prepare your Excel stuff
        Set XL = new Excel.Application
        XL.Visible = True
        Set WB = XL.Workbooks.Add 
        WB.Activate
        Set WKS = WB.ActiveSheet ' Default: The first sheet in the newly created book
    
        ' Read your data here
        set db = currentdb()
        set rec = db.openrecordset("tblSampleData")
    
        ' A simple table that will show the data from rec
        ' i and j will be the coordiantes of the active cell in your worksheet
        with rec
            .movefirst
    
            ' The table headers
            i = 1
            j = 1
            for each f in .fields
                WKS.cells(i,j).value = f.name
                j = j + 1
            next f
    
            ' The table data
            do
                i = i+1
                j = 1
                for each f in .Fields
                    WKS.cells(i,j).value = f.value
                    j = j+1
                next f     
                .moveNext     
            loop until .EOF
        end with
    end sub
    

    If you want to format the cells, you can use the WKS.cells(i,j) (or WKS.range(...)) properties.

    Take a look at the link I leaved before (which Siddarth Rout was kind to move to the comments).

    I hope this helps you

提交回复
热议问题