Macro para crear un nuevo archivo de un archivo existente con un botón

Dante otra vez pidiendo tu apoyo

Te comento mi solicitud el archivo que has venido apoyándome tiene un botón que se llama crear archivo, el objetivo de este botón es crear un archivo nuevo en formato pdf, esta hoja tiene varias macros, las cuales son para ocultar y mostrar filas, ya hay una macro iniciada pero me da algunos errores y el archivo nuevo lo crea en formato excel y como el archivo tiene varias formulas de subtotales da error al final, por lo que quería ver si puedes revisarla.

Este es el código que tiene la hoja de créditos el cual al momento de presionar el botón ocultar filas únicamente deja las filas que en realidad se necesitan y es así como esta la imagen que se necesita que se cree el nuevo archivo en pdf, adjunto el código

Sub Crear_Archivo()
    Dim fila_ini As Double, col1 As String, c As Range
    Dim l2 As Workbook, h2 As Worksheet, i As Long
    Dim l1 As Workbook, h1 As Worksheet
    Application.ScreenUpdating = False
    Application.CopyObjectsWithCells = False
    Application.DisplayAlerts = False
    Set l1 = ThisWorkbook
    Set h1 = ActiveSheet
    Call desproteger
    fila_ini = 7
    col1 = "J"
    h1.Cells.EntireRow.Hidden = False
    h1.Copy
    Set l2 = ActiveWorkbook
    Set h2 = l2.Sheets(1)
    'For Each c In h2.UsedRange
        'c.Value = c.Value
    'Next
    For i = h2.Range("J" & Rows.Count).End(xlUp).Row To fila_ini Step -1
        If h2.Cells(i, col1) = 0 Then
            h2.Cells(i, col1).EntireRow.Delete
        End If
    Next i
    h1.Range("A1:I2").Copy h2.Range("A1")
    'h2.Range("A1").PasteSpecial xlPasteAll
    h2.Protect ("regional2018")
    l2.SaveAs ThisWorkbook.Path & "\" & "Analisis_de_Creditos.xlsx"
    l2.Close False
    Application.ScreenUpdating = True
    Application.CopyObjectsWithCells = True
    Call proteger
    MsgBox "Hoja guardada en un nuevo archivo."
End Sub
'
Sub mostrar_ocultar()
desproteger
    fila_ini = 7
    col1 = "J"
        '
    For i = fila_ini To Range("J" & Rows.Count).End(xlUp).Row
        If Cells(i, col1) > 0 Then
            Cells(i, col1).EntireRow.Hidden = False
        Else
            Cells(i, col1).EntireRow.Hidden = True
        End If
    Next i
    proteger
End Sub
Sub mostrar_FILAS()
desproteger
    fila_ini = 1
    col1 = "J"
    '
    For i = fila_ini To 200
            Cells(i, col1).EntireRow.Hidden = False
    Next i
    proteger
End Sub
Sub proteger()
Worksheets(3).Select
ActiveSheet.Protect ("regional2018")
End Sub
Sub desproteger()
Worksheets(3).Select
ActiveSheet.Unprotect ("regional2018")
End Sub

Para el caso de los débitos necesitamos lo mismo, para lo cual adjuntamos imagen sobre el boton de crear archivo, es decir que al momento de crear el nuevo archivo sea en pdf y se vea como en imagen

Al igual adjunto codigo el cual me da problemas para crearlo y lo hace en Excel

Y esta el la ultima hoja que tambien necesito crear un archivo nuevo en pdf

No me deja pegar los demás códigos por el exceso de los caracteres, pero puedo agregarlo despues, muy agradecida

1 respuesta

Respuesta
2

Te anexo nuevos códigos. Realiza lo siguiente:

- En un nuevo módulo pon el siguiente código:

Sub Pdf_Creditos()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Análisis de Créditos", "Analisis_de_Creditos")
End Sub
'
Sub Pdf_Debitos()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Análisis de Débitos", "Analisis_de_Debitos")
End Sub
'
Sub Crear_Pdf(hoja, nombre)
  Dim i As Long
  Dim h1 As Worksheet
  '
  Application.ScreenUpdating = False
  Application.CopyObjectsWithCells = False
  Application.DisplayAlerts = False
  '
  Set h1 = Sheets(hoja)
  h1.Unprotect ("regional2018")
  h1.Cells.EntireRow.Hidden = False
  For i = 7 To h1.Range("J" & Rows.Count).End(3).Row
    If h1.Range("J" & i) = 0 Then h1.Range("J" & i).EntireRow.Hidden = True
  Next i
  h1.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "\" & nombre & ".pdf"
  '
  Application.ScreenUpdating = True
  Application.CopyObjectsWithCells = True
  h1.Cells.EntireRow.Hidden = False
  h1.Protect ("regional2018")
  MsgBox "Hoja: " & hoja & ". Guardada en un nuevo archivo: " & nombre
End Sub

- Para el botón CREARARCHIVO de la hoja créditos asigna la macro "Pdf_Creditos" 

- Para el botón CREARARCHIVO de la hoja débitos asigna la macro "Pdf_Debitos"

La macro se encargar de desproteger, ocultar filas y guardar como pdf.

Excelente Dante ya hice la prueba con el archivo de análisis de créditos y funciona excelente.

ahora con el caso de análisis de débitos crea el archivo nuevo, pero cuando se abre para ver como quedo lo crea completo sin las filas ocultas o como esta el archivo al momento de generarlo como nuevo, en el código de análisis de créditos la columna es la "j", la macro para ocultar y mostrar filas, la cual funciona excelente

Set h1 = Sheets(hoja)
  h1.Unprotect ("regional2018")
  h1.Cells.EntireRow.Hidden = False
  For i = 7 To h1.Range("J" & Rows.Count).End(3).Row
    If h1.Range("J" & i) = 0 Then h1.Range("J" & i).EntireRow.Hidden = True
  Next i
  h1.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "\" & nombre & ".pdf"

En la hoja de análisis de débitos es  la columna "E" donde la macro funciona para ocultar y mostrar filas, no se si se debe cambiar o agregar otro código especifico por la columna especifica "E", de esta hoja porque cuando se presiona el archivo crear archivo lo genera completo 

Sub Crear_Archivo2()
    Dim fila_ini As Double, col1 As String, c As Range
    Dim l2 As Workbook, h2 As Worksheet, i As Long
    Dim l1 As Workbook, h1 As Worksheet
    Application.ScreenUpdating = False
    Application.CopyObjectsWithCells = False
    Application.DisplayAlerts = False
    Set l1 = ThisWorkbook
    Set h1 = ActiveSheet
    Call desproteger
    fila_ini = 7
    col1 = "E"
    h1.Cells.EntireRow.Hidden = False
    h1.Copy
    Set l2 = ActiveWorkbook
    Set h2 = l2.Sheets(1)
    'For Each c In h2.UsedRange
        'c.Value = c.Value
    'Next
    For i = h2.Range("e" & Rows.Count).End(xlUp).Row To fila_ini Step -1
        If h2.Cells(i, col1) = 0 Then
            h2.Cells(i, col1).EntireRow.Delete
        End If
    Next i
    h1.Range("A1:I2").Copy h2.Range("A1")
    'h2.Range("A1").PasteSpecial xlPasteAll
    h2.Protect ("regional2018")
    l2.SaveAs ThisWorkbook.Path & "\" & "Analisis_de_Debito.xlsx"
    l2.Close False
    Application.ScreenUpdating = True
    Application.CopyObjectsWithCells = True
    Call proteger
    MsgBox "Hoja guardada en un nuevo archivo."
End Sub
'---------------------
Sub mostrar_ocultar()
desproteger
    fila_ini = 7
    col1 = "E"
        '
    For i = fila_ini To Range("E" & Rows.Count).End(xlUp).Row
        If Cells(i, col1) > 0 Then
            Cells(i, col1).EntireRow.Hidden = False
        Else
            Cells(i, col1).EntireRow.Hidden = True
        End If
    Next i
    proteger
End Sub
Sub mostrar_FILAS()
desproteger
    fila_ini = 1
    col1 = "E"
    '
    For i = fila_ini To 200
            Cells(i, col1).EntireRow.Hidden = False
    Next i
    proteger
End Sub
Sub proteger()
Worksheets(4).Select
ActiveSheet.Protect ("regional2018")
End Sub
Sub desproteger()
Worksheets(4).Select
ActiveSheet.Unprotect ("regional2018")
End Sub

y este es el código que tiene la hoja 2, pero en la pregunta original no me deja subirla por la cantidad de caracteres 

Y para la otra hoja de junta directiva imprimir me crea el archivo completo también, no genera con las filas ocultas, y la macro de ocultar y mostrar filas esta en las columnas C y D 

voy a escribirte en otra pedir mas información porque tengo pendiente la ultima hoja

como te decía Dante, con el caso de la hoja junta directiva imprimir tengo el mismo inconveniente de que cuando genera el nuevo archivo no lo realiza en base a las macros de ocultar y mostrar, no se si sera por las columnas de cada hoja porque en los créditos es la columna J, en la de Débitos es la E y la de junta directiva son las columnas C y D.

la macro que tiene el archivo actual de la hoja junta directiva es la siguiente 

Sub Crear_Archivo3()
    Dim fila_ini As Double, col1 As String, c As Range
    Dim l2 As Workbook, h2 As Worksheet, i As Long
    Dim l1 As Workbook, h1 As Worksheet
    Application.ScreenUpdating = False
    Application.CopyObjectsWithCells = False
    Application.DisplayAlerts = False
    Set l1 = ThisWorkbook
    Set h1 = ActiveSheet
    Call desproteger
    fila_ini = 4
    col1 = "C"
    h1.Cells.EntireRow.Hidden = False
    h1.Copy
    Set l2 = ActiveWorkbook
    Set h2 = l2.Sheets(1)
    For Each c In h2.UsedRange
      c.Value = c.Value
    Next
    For i = h2.Range("C" & Rows.Count).End(xlUp).Row To fila_ini Step -1
        If h2.Cells(i, col1) = 0 Then
            h2.Cells(i, col1).EntireRow.Delete
        End If
    Next i
    h1.Range("A1:I2").Copy h2.Range("A1")
    'h2.Range("A1").PasteSpecial xlPasteAll
    h2.Protect ("regional2018")
    l2.SaveAs ThisWorkbook.Path & "\" & "Junta_directiva.xlsx"
    l2.Close False
    Application.ScreenUpdating = True
    Application.CopyObjectsWithCells = True
    Call proteger
    MsgBox "Hoja guardada en un nuevo archivo."
End Sub
'-------------------
Sub mostrar_ocultar()
desproteger
    fila_ini = 8
    col1 = "C"
    col2 = "D"
    '
    For i = fila_ini To Range("C" & Rows.Count).End(xlUp).Row
        If Cells(i, col1) > 0 Or Cells(i, col2) > 0 Then
            Cells(i, col1).EntireRow.Hidden = False
        Else
            Cells(i, col1).EntireRow.Hidden = True
        End If
    Next i
proteger
End Sub
Sub mostrar_FILAS()
desproteger
    fila_ini = 1
    col1 = "C"
    col2 = "D"
    '
    For i = fila_ini To 200
            Cells(i, col1).EntireRow.Hidden = False
    Next i
    proteger
End Sub
Sub proteger()
Worksheets(5).Select
ActiveSheet.Protect ("regional2018")
End Sub
Sub desproteger()
Worksheets(5).Select
ActiveSheet.Unprotect ("regional2018")
End Sub

este es el código que yo pegue que tu me enviaste y adiciona la de junta directiva 

Sub Pdf_Creditos()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Análisis de Créditos", "Analisis_de_Creditos")
End Sub
'
Sub Pdf_Debitos()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Análisis de Débitos", "Analisis_de_Debitos")
End Sub
'
Sub Pdf_Transferencia()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Junta Directiva (Imprimir)", "Junta Directiva (Imprimir)")
End Sub
'
Sub Crear_Pdf(hoja, nombre)
  Dim i As Long
  Dim h1 As Worksheet
  '
  Application.ScreenUpdating = False
  Application.CopyObjectsWithCells = False
  Application.DisplayAlerts = False
  '
  Set h1 = Sheets(hoja)
  h1.Unprotect ("regional2018")
  h1.Cells.EntireRow.Hidden = False
  For i = 7 To h1.Range("J" & Rows.Count).End(3).Row
    If h1.Range("J" & i) = 0 Then h1.Range("J" & i).EntireRow.Hidden = True
  Next i
  h1.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "\" & nombre & ".pdf"
  '
  Application.ScreenUpdating = True
  Application.CopyObjectsWithCells = True
  h1.Cells.EntireRow.Hidden = False
  h1.Protect ("regional2018")
  MsgBox "Hoja: " & hoja & ". Guardada en un nuevo archivo: " & nombre
End Sub

ojala puedas seguir ayundadome Dante

Los créditos es la columna J, en la de Débitos es la E y la de junta directiva son las columnas C y D

Prueba esto:

Sub Pdf_Creditos()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Análisis de Créditos", "Analisis_de_Creditos", "J", "J")
End Sub
'
Sub Pdf_Debitos()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Análisis de Débitos", "Analisis_de_Debitos", "E", "E")
End Sub
'
Sub Pdf_Transferencia()
                 'Nombre de la hoja   ,  nombre del archivo
  Call Crear_Pdf("Junta Directiva (Imprimir)", "Junta Directiva (Imprimir)", "C", "D")
End Sub
'
Sub Crear_Pdf(hoja, nombre, col1, col2)
  Dim i As Long
  Dim h1 As Worksheet
  '
  Application.ScreenUpdating = False
  Application.CopyObjectsWithCells = False
  Application.DisplayAlerts = False
  '
  Set h1 = Sheets(hoja)
  h1.Unprotect ("regional2018")
  h1.Cells.EntireRow.Hidden = False
  For i = 7 To h1.Range(col1 & Rows.Count).End(3).Row
    If h1.Range(col1 & i) = 0 And h1.Range(col2 & i) = 0 Then
      h1.Range(col1 & i).EntireRow.Hidden = True
    End If
  Next i
  h1.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "\" & nombre & ".pdf", _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, OpenAfterPublish:=False
  '
  Application.ScreenUpdating = True
  Application.CopyObjectsWithCells = True
  h1.Cells.EntireRow.Hidden = False
  h1.Protect ("regional2018")
  MsgBox "Hoja: " & hoja & ". Guardada en un nuevo archivo: " & nombre
End Sub

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas