Não são raras as ocasiões onde precisamos entregar os nossos relatórios em planilhas Excel. Por vezes estas nem mesmo precisam de formatação, apenas dos dados.
Em outras ocasiões vários processos geram distintas planilhas MS Excel e precisamos a posteriori deixar todas num mesmo workbook. Segue o modo de fazermos isso:
Public Sub YourSub()Dim objexcel As Excel.ApplicationDim wbexcel As Excel.WorkbookDim wbExists As BooleanSet objexcel = CreateObject("excel.Application")'This is a bad way of handling errors. We should''instead check for the file existing, having correct''permissions, and so on, and actually stop the process''if an unexpected error occurs.'On Error GoTo OpenwbwbExists = FalseSet wbexcel = objexcel.Workbooks.Open("C:\REPORT1.xls")wbExists = TrueOpenwb:On Error GoTo 0If Not wbExists ThenSet wbexcel = objexcel.Workbooks.Add()End IfCopyToWorkbook wbexcelEndSubPrivate Sub CopyToWorkbook(objWorkbook As Excel.Workbook)Dim newWorksheet As Excel.Worksheetset newWorksheet = objWorkbook.Worksheets.Add()'Copy stuff to the worksheet here'End Sub
Tags: VBA, Excel, Access, Sheets, Workbook, Worksheet, Copy