Access - Exportar informe a Excel con formato

 
Vista:

Exportar informe a Excel con formato

Publicado por Cristina (3 intervenciones) el 06/10/2021 10:22:35
Buenos días,

Me gustaría exportar un informe a Excel para cada uno de los eventos registrados en mi bbdd (Access 2016). Cada informe de evento consta de 10 sub-informes, que me gustaría separar en distintas Hojas si es posible y sino, al menos, darle un formato básico (títulos en negrita y un poco de orden en el tamaño y color de las celdas).

Inicialmente, usé este comando que me permite abrir la información que quiero y crear el documento de Excel:
DoCmd.OpenReport "EventArchive", acViewPreview, , "[EventID]=" & Me.EventID, acHidden
DoCmd.OutputTo acOutputReport, "EventArchive", acFormatXLS, "\\ubicacion\folder\Events archive\" & [Event] & ".xls", False
DoCmd.Close acReport, "EventArchive"

Encontré en Internet códigos que sirven para dar formato a un Excel, pero como estoy empezando a aprender VBA no sé en qué orden debo colocar las líneas para conseguir mi objetivo de crear un documento en la carpeta deseada y formatearlo.

Les dejo aqui el codigo que encontre, por si alguien me sabe explicar como usarlo.

Muchas gracias

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
Private Sub ExportOverviewToExcel_Click()
 
On Error GoTo SubError
 
Dim newapp As Object
Dim wb As Object
Dim ws As Object
Dim rng As Object
Dim lngLastCol As Long
Dim x As Long
Set newapp = CreateObject("excel.application")
Set wb = newapp.Workbooks.Open(strExcelPath)
Set ws = wb.Sheets(lngWorksheetPos)
 
ws.Cells.WrapText = False
ws.Rows(1).Font.Bold = True
ws.PageSetup.Orientation = 2
ws.PageSetup.Zoom = False
ws.PageSetup.FitToPagesTall = False
ws.PageSetup.FitToPagesWide = 1
ws.Columns.AutoFit
lngLastCol = ws.Cells(1, ws.Columns.Count).End(-4159).Column
For x = 1 To lngLastCol - 1
    If ws.Columns(x).ColumnWidth > 35 Then  'reduce and wrap
        ws.Columns(x).ColumnWidth = 35
        ws.Columns(x).WrapText = True
    End If
Next x
 
For Each rng In ws.UsedRange
 
    If IsDate(rng) And IsNumeric(rng) = False Then
    'If IsDate(rng) Then
        rng = Format(rng, "mm/dd/yyyy")
        rng.NumberFormat = "mm/dd/yyyy;@"
    End If
    rng.HorizontalAlignment = -4131
Next rng
 
With ws.PageSetup
    .PrintTitleRows = "$1:$1"
    .PrintTitleColumns = ""
End With
With ws.PageSetup
    .LeftHeader = ""
    .CenterHeader = ""
    .RightHeader = ""
    .LeftFooter = ""
    .CenterFooter = ""
    .RightFooter = ""
    .PrintHeadings = False
    .PrintGridlines = True
    '.PrintQuality = 600
    .CenterHorizontally = False
    .CenterVertically = False
    .Orientation = 2
    .Draft = False
    .BlackAndWhite = False
    .Zoom = False
    .FitToPagesWide = 1
    .FitToPagesTall = False
    .OddAndEvenPagesHeaderFooter = False
    .DifferentFirstPageHeaderFooter = False
    .ScaleWithDocHeaderFooter = True
    .AlignMarginsHeaderFooter = True
    .EvenPage.LeftHeader.Text = ""
    .EvenPage.CenterHeader.Text = ""
    .EvenPage.RightHeader.Text = ""
    .EvenPage.LeftFooter.Text = ""
    .EvenPage.CenterFooter.Text = ""
    .EvenPage.RightFooter.Text = ""
    .FirstPage.LeftHeader.Text = ""
    .FirstPage.CenterHeader.Text = ""
    .FirstPage.RightHeader.Text = ""
    .FirstPage.LeftFooter.Text = ""
    .FirstPage.CenterFooter.Text = ""
    .FirstPage.RightFooter.Text = ""
End With
 
If blLeaveOpen = True Then
    wb.Save
    newapp.Visible = True
Else
    wb.Close (True)
    newapp.DisplayAlerts = False
    newapp.Quit
End If
 
 
'Error handling
SubExit:
Exit Sub
 
SubError:
'MsgBox "Error number: " & Err.Number & "*" & Err.Description, vbCritical + vbOKOnly, "An error occurred"
'AnyProgressLabelFormName.Visible=False
MsgBox "The following error has occurred in the function 'FormatExcelOutput': " _
& vbNewLine & vbNewLine & "If reporting this error, please STOP and " _
& "include a screenshot of this error" _
& vbNewLine & "as well as the entire screen/program" _
& vbNewLine & vbNewLine & "Error description:  " & Err.Description _
& vbNewLine & "Error number:  " & Err.Number, vbCritical, "  "
GoTo SubExit
 
End Sub
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Vba Access
Val: 485
Plata
Ha aumentado 1 puesto en Access (en relación al último mes)
Gráfica de Access

Exportar informe a Excel con formato

Publicado por Vba Access (26 intervenciones) el 06/10/2021 18:37:28
Hola.
Es algo complicado explicarte como usarlo ya que el objeto excel tiene muchos metodos y propiedades. Es imposible aprenderse cada una, pero si se puede aprender las mas importantes.

Te dejo la documentacion, ahi te explica para que sirve cada metodo y propiedad.
Application object (Excel)
https://docs.microsoft.com/en-us/office/vba/api/excel.application(object)

Tambien te dejo un ejemplo de como exporto una tabla con formato a excel, es algo sencillo, espero te sirva.
https://youtu.be/2bDuTZWbVMg


Te dejo mi canal de YouTube talvez algún video te sea útil.
https://www.youtube.com/c/VBAAccess?sub_confirmation=1
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Exportar informe a Excel con formato

Publicado por Cristina (3 intervenciones) el 07/10/2021 12:34:41
Muchas gracias, el video de YouTube me ha resultado muy útil.

Yo lo he colocado en el private sub de un boton que tengo en un formulario, pero me aparece el siguiente error de compilacion y me subraya en el debugger la línea del título del private sub:

"Compile error: user-defined type not defined"

A que se debe este error?

Muchas gracias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Vba Access
Val: 485
Plata
Ha aumentado 1 puesto en Access (en relación al último mes)
Gráfica de Access

Exportar informe a Excel con formato

Publicado por Vba Access (26 intervenciones) el 09/10/2021 21:15:41
Hola.
No me queda tu error.

Si quieres escribe al correo de contacto y descríbeme con imágenes tu situación.

[email protected]
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar