sábado, 28 de agosto de 2010

Macro de VisualBasic para pasar a PDF una hoja de excel.

Con este Macro de VB pasaremos nuestra hoja de excel a PDF usando el PDF creator. Para ello, es necesario tener instalado el PDFCreator (disponible aquí) y después hace falta ir al editor del Visual Basic (Alt+F11) desde la hoja de excel, y activar la casilla PDFCreator que está en:
Menu Herramientas->Referencias

El código está sacado de esta página. (Muchas gracias, Ken Plus por tu aportación)

Se ha modificado para conseguir que compare el mes en el que se ha guardado el archivo excel con el mes escrito en la casilla k54. De este modo si es el mismo mes, el nombre del archivo será sudoku.pdf y si es el mes siguiente será sudoku2.pdf.

Para ello se ha modificado esta parte del código:

  '/// Change the output file name here! ///

sPDFName = "testPDF.pdf"
Por este otro:

    '/// Change the output file name here! ///  

Dim MesGuardado
Dim MesPlanning
MesPlanning = Range("k54").Value2
MesGuardado = Month(FileDateTime(Application.ActiveWorkbook.FullName))
If MesPlanning = MesGuardado Then sPDFName = "sudoku.pdf"
If MesPlanning = MesGuardado + 1 Then sPDFName = "sudoku2.pdf"




El macro entero es este:

Sub PrintToPDF_Early()
'Author : Ken Puls (www.excelguru.ca)
'Macro Purpose: Print to PDF file using PDFCreator
' (Download from http://sourceforge.net/projects/pdfcreator/)
' Designed for early bind, set reference to PDFCreator

Dim pdfjob As PDFCreator.clsPDFCreator
Dim sPDFName As String
Dim sPDFPath As String

'/// Change the output file name here! ///
Dim MesGuardado
Dim MesPlanning
MesPlanning = Range("k54").Value2
MesGuardado = Month(FileDateTime(Application.ActiveWorkbook.FullName))
If MesPlanning = MesGuardado Then sPDFName = "sudoku.pdf"
If MesPlanning = MesGuardado + 1 Then sPDFName = "sudoku2.pdf"

sPDFPath = ActiveWorkbook.Path & Application.PathSeparator

'Check if worksheet is empty and exit if so
If IsEmpty(ActiveSheet.UsedRange) Then Exit Sub

Set pdfjob = New PDFCreator.clsPDFCreator

With pdfjob
If .cStart("/NoProcessingAtStartup") = False Then
MsgBox "Can't initialize PDFCreator.", vbCritical + _
vbOKOnly, "PrtPDFCreator"
Exit Sub
End If
.cOption("UseAutosave") = 1
.cOption("UseAutosaveDirectory") = 1
.cOption("AutosaveDirectory") = sPDFPath
.cOption("AutosaveFilename") = sPDFName
.cOption("AutosaveFormat") = 0 ' 0 = PDF
.cClearCache
End With

'Print the document to PDF
ActiveSheet.PrintOut copies:=1, ActivePrinter:="PDFCreator"

'Wait until the print job has entered the print queue
Do Until pdfjob.cCountOfPrintjobs = 1
DoEvents
Loop
pdfjob.cPrinterStop = False

'Wait until PDF creator is finished then release the objects
Do Until pdfjob.cCountOfPrintjobs = 0
DoEvents
Loop
pdfjob.cClose
Set pdfjob = Nothing
End Sub

No hay comentarios: