简体   繁体   中英

Convert Excel rows to PDF pages using VBA

I have data in Excel with student names and their marks. I want to export the data to PDF using VBA macro where each student details appear on a different PDF page. So if there are 20 students then there will be 20 pages in single PDF. Each student name will form heading of the PDF page and their marks will appear in a table below the heading.

I have a table like this in Excel

student name  -  erp  -    science marks        -geography marks
                           test1  test2          test1  test2  test3
peter         -  12        15      9.5           15      7      11
jack          -  13        16      11            10      9      13

How can I export this data in a PDF like student.pdf , where page1 will have peter name as heading and the sum of his science marks and geography marks. Similarly, page2 will have jack's name and sum of his marks. How can I do that?

Also, the number of students is dynamic. So I have to count the number of students and that will be the count of my PDF. How do I do that?

code so far

Sub convertTopdf()
Dim ws As Worksheet
Dim lastRow As Long

ChDir "C:\Users\Dell\Desktop"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\Dell\Desktop\task_excel\POD.pdf", OpenAfterPublish:=True

Set ws = ActiveWorkbook.ActiveSheet
With ws
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With

MsgBox "The last row which has data in Col A of Sheet1 is " & lastRow

End Sub

If you print multiple selected ranges, then each range will be printed to a different page. If you were printing multiple areas on a single page, this would be as simple as:

Range("Sheet1!C5:D6,Sheet1!D13:E14").Select
ActiveWindow.SelectedSheets.PrintOut Copies:=1

So if you want each row to be printed to a different page, just use a FOR loop to define the ranges and print the sheet like this...

myrange = "A1:C1"
lastRow = Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row
For myRow = 2 To lastRow
   myrange = myrange & ",A" & myRow & ":C" & myRow
Next
Range(myrange).Select
Application.Dialogs(xlDialogPrint).Show

This will open a print dialog, and you can select the printer of your choice (including PDF). I assume that you have the ability to print to PDF in some way - if you have Excel 2010, for example, you can simply select "Adobe PDF" as your printer.

Be sure to select "print selection" and not the entire worksheet :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM