Excel VBA - UsingVBA to create a new, formatted workbook

后端 未结 4 1785
耶瑟儿~
耶瑟儿~ 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条回答
  •  Happy的楠姐
    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) '<<

    '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
    

提交回复
热议问题