By Ajeet Kumar
EXCEL VBA TO GENERATE PDF FILE FROM A WORKSHEET
Following logical steps are used in the following procedure:
Sub pGenPDF()
Dim objWApp As Object
Dim strPath As String
On Error GoTo lblPDF
strPath = ThisWorkbook.Path & Application.PathSeparator
Set objWApp = CreateObject("WORD.Application")
With objWApp
.Documents.Add
.Visible = True
End With
Range("A1:D200").Copy
objWApp.ActiveDocument.Content.Paste
Application.CutCopyMode = False
objWApp.Documents(1).Tables(1).PreferredWidth = 0
objWApp.Documents(1).Tables(1).Rows.Alignment = 1
objWApp.ActiveDocument.SaveAs2 strPath & "MyPDF.pdf", 17
objWApp.ActiveDocument.Close SaveChanges:=0
objWApp.Quit
Set objWApp = Nothing
MsgBox "PDF File Generated.", vbInformation
lblPDF:
If err.Number <> 0 Then
MsgBox "Error Number: " & err.Number & vbCrLf & "Error Description: " & err.Description
End If
Application.ScreenUpdating = True
End Sub
---------------------------------------------------------------------------------------------
Following logical steps are used in the following procedure:
- An instance of Word Application Object is created using late binding.
- An instance of Word Document is created and added to Documents Collection.
- The instance of Word Documents is made visible.
- The target range of worksheet is copied and pasted to the Word Document.
- The Word Table is formatted using the Enumeration constants in Numeric terms.
- The Document is saved as PDF File.
- The Document is closed.
- The Word Application is closed.
- The Word Application Object is set to Nothing to release the memory.
Sub pGenPDF()
Dim objWApp As Object
Dim strPath As String
On Error GoTo lblPDF
strPath = ThisWorkbook.Path & Application.PathSeparator
Set objWApp = CreateObject("WORD.Application")
With objWApp
.Documents.Add
.Visible = True
End With
Range("A1:D200").Copy
objWApp.ActiveDocument.Content.Paste
Application.CutCopyMode = False
objWApp.Documents(1).Tables(1).PreferredWidth = 0
objWApp.Documents(1).Tables(1).Rows.Alignment = 1
objWApp.ActiveDocument.SaveAs2 strPath & "MyPDF.pdf", 17
objWApp.ActiveDocument.Close SaveChanges:=0
objWApp.Quit
Set objWApp = Nothing
MsgBox "PDF File Generated.", vbInformation
lblPDF:
If err.Number <> 0 Then
MsgBox "Error Number: " & err.Number & vbCrLf & "Error Description: " & err.Description
End If
Application.ScreenUpdating = True
End Sub
---------------------------------------------------------------------------------------------
No comments:
Post a Comment