Views

Histats

Vitrine

VBA Access - Adicionando novas Sheets no mesmo Workbook - Adding new sheets to Excel




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.Application
    Dim wbexcel As Excel.Workbook
    Dim wbExists As Boolean
    Set 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 Openwb
    wbExists = False
    Set wbexcel = objexcel.Workbooks.Open("C:\REPORT1.xls")
    wbExists = True

Openwb:
    On Error GoTo 0
    If Not wbExists Then
        Set wbexcel = objexcel.Workbooks.Add()
    End If

    CopyToWorkbook wbexcel
EndSub

Private Sub CopyToWorkbook(objWorkbook As Excel.Workbook)
    Dim newWorksheet As Excel.Worksheet
    set newWorksheet = objWorkbook.Worksheets.Add()

    'Copy stuff to the worksheet here'
End Sub

Tags: VBA, Excel, Access, Sheets, Workbook, Worksheet, Copy


LinkWithinBrazilVBAExcelSpecialist

Related Posts Plugin for WordPress, Blogger...