Excel VBA - UsingVBA to create a new, formatted workbook

后端 未结 4 1711
耶瑟儿~
耶瑟儿~ 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

    0 讨论(0)
  • 2021-01-25 07:39

    You don't give a lot of details, so I can't give you a lot of details in return. But here's how I would do it:

    1. Create a new workbook manually with two sheets
    2. On one sheet, add an External Data table that returns a list of supplier's name like SELECT SupplierName FROM tblSuppliers WHERE Active=True; or something like that.
    3. Create a workbook-level named range that dynamically expands with that query table
    4. On the second sheet, add an External Data table like SELECT * FROM Orders WHERE SupplierName=? (This will be a parameter query). Start that external data table in row 3
    5. I row, put a combobox box that points back to the supplier list.

    Now the VBA is simple

    ThisWorkbook.RefreshAll
    

    Instead of one sheet per supplier, you'll have one sheet on which you can change the supplier. Here are the skills you'll need

    • Create an external data table
    • Create a parameter query (old reference http://www.dicks-clicks.com/excel/ExternalData6.htm)
    • Create dynamically expanding range name
    • Add a combobox or data validation that points to a range on a different sheet
    • That SQL above is obviously not right, but I assume you can write the correct SQL statement

    You should be able to find details on all that, but if not, post another question.

    0 讨论(0)
  • 2021-01-25 07:45
    Option Compare Database
    Public Function format(filepath, sheetname)
    
    
    Set xls = CreateObject("EXCEL.APPLICATION")
    xls.screenupdating = False
    xls.displayalerts = False
    xls.Visible = True
    xls.workbooks.Open filepath
    Set xlsdd = xls.ActiveWorkbook
    

    'deleting headers

    xls.Range("1:1").Select
    xls.Selection.Delete Shift:=xlUp
    

    'adding one column

        xls.Columns("A:A").Select
       xls.Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    
    'adding 5 rows
    

    'ActiveWorkbook.Sheets("sheet1").Select

    xls.Rows("1:5").Insert Shift:=xlDown
    

    'fetching rows from access and putting them into excel

    strsql = "select top 5 " & sheetname & ".* into top5_records from " & sheetname
    DoCmd.RunSQL strsql
    outputFileName = "C:\Users\hp\Desktop\top5_records.xls"
     DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "top5_records",    outputFileName, True
    

    'then open that excel and copy the rows

    Set xls2 = CreateObject("EXCEL.APPLICATION")
    xls2.screenupdating = False
    xls2.displayalerts = False
    xls2.Visible = True
    xls2.workbooks.Open outputFileName
    Set xlsdd2 = xls.ActiveWorkbook
     xls2.Rows("1:5").Select
     xls2.Selection.Copy
      xls.Cells(1, 1).Select
     xls.activesheet.Paste
    
    
    
         '  Dim currdb As DAO.Database
    '  Dim rst As DAO.Recordset
    '
    '  Set currdb = CurrentDb
    '  Set rst = currdb.OpenRecordset(strsql) '<<<Opens query recordset via DAO
    '  rst.MoveLast
    '  rowsToReturn = rst.RecordCount
    '  Set rng = xls.Cells(1, 1)
    '  'copy specified number of records to worksheet
    '
    'rng.CopyFromRecordset rst, rowsToReturn '<<<Gets all records in recordset
    

    'making first 6th row to be bold

     xls.Rows("6:6").Select
      With xls.Selection.Font
      .Bold = True
      .Name = "Arial"
        .Size = 10
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
    End With
    

    'autofit the data

    xls.Sheets(sheetname).Cells.Columns.autofit
    xls.CutCopyMode = False
    With xlsdd
    .Save
    .Close
    End With
    xls.Visible = False
    
    Set xlsdd = Nothing
    Set xls = Nothing
    
    End Function
    
    0 讨论(0)
  • 2021-01-25 07:45

    You can define column/row widths to a static pixel amount or auto-fit, things like bold are a pre-defined

    Example

    Selection.Font.Bold = True

    You can also make a template spreadsheet, copy the contents into the template and save as. Your post does not indicate how much formatting actually needs to be done.

    0 讨论(0)
提交回复
热议问题