thank you for the explanation, but can we do it using VBA instead doing it manually one by one?
Hello Bigme,
Thank you for your feedback. Formatting data into Excel Tables can be troublesome with VBA. Instead, let's try an easier way.
I have modified the VBA code that takes sections of data from the
source worksheet, pastes them into the
template worksheet, saves each section as a separate
PDF file, and repeats the process until all sections have been saved as
PDFs. And, the good news is, this time you can use the raw data without formatting them into Excel tables. Here are the steps to do so:
- Copy the VBA code to a module and Run it.
Code:
Sub PrintPDF()
'Produced by ExcelDemy
Set Sh1 = Sheets("source")
Set sh2 = Sheets("template")
Set Rng1 = Sh1.Range("A1:D22")
Set Rng2 = sh2.Range("A8")
Start = 1
savePath = "C:\Users\PC 05\Downloads\Bigme\Sheet"
Number = 1
iRows = 1
iColumns = 1
For i = 1 To Rng1.Rows.Count
If Rng1.Cells(i, 4).Value = "" Then
Ending = i - 1
Range(Rng2.Cells(1, 1), Rng2.Cells(iRows, iColumns)).ClearContents
Set PrintRng = Range(Rng1.Cells(Start, 1), Rng1.Cells(Ending, 4))
PrintRng.Copy Destination:=Rng2
savePath = savePath & Str(Number) & ".pdf"
sh2.ExportAsFixedFormat Type:=xlTypePDF, Filename:=savePath, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Start = i + 1
Number = Number + 1
savePath = "C:\Users\PC 05\Downloads\Bigme\Sheet"
iRows = PrintRng.Rows.Count
iColumns = PrintRng.Columns.Count
End If
Next i
End Sub
- Consequently, the tables will be automatically saved in the given file path.
- Open any file to check if the printed template is accurate.
Code Explanation:
Code:
savePath = "C:\Users\PC 05\Downloads\Bigme\Sheet"
Don't forget to modify the file path where you want to save the pdf files. Also, change the file names in this line as you desire. For example, I have set the file names as
Sheet 1,
Sheet 2, and so on.
Code:
Set Sh1 = Sheets("source")
Set sh2 = Sheets("template")
Set Rng1 = Sh1.Range("A1:D22")
Set Rng2 = sh2.Range("A8")
This section of the code is the input section. Make sure you take an extra row after the last table while declaring the
Set Rng1. For example. the last row of the last table was
D21. So, I have taken
D22 as the last row.
Tips: Instead of printing tables, you can directly copy and paste tables as images or
HTML tables into Email body using VBA. For details, click on
How to Use Excel VBA to Paste Table or Range into Email Body.
I have attached the Excel workbook. Kindly let me know if it works for you.
Regards.