简体   繁体   中英

Assign filename to pdf from cell value

I have a macro that saves the excel file into a PDF one:

   Sub PDF()
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:="C:\Report.pdf", _
            OpenAfterPublish:=False
    End Sub

How do I assign the pdf name to a value in a specific cell in excel? And how I do specify the save directory as the same where the excel file is located?

If you modify your code like below, your ActiveSheet will get exported as a .PDF to the same folder as the ActiveWorkbook , and with the name defined in cell A1 of the ActiveSheet .

Sub PDF()
    Dim SaveAsStr As String

    SaveAsStr = ActiveWorkbook.Path & "\" & ActiveSheet.Range("A1").Value

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=SaveAsStr & ".pdf", _
        OpenAfterPublish:=False
End Sub

Note that you may want to refine this code a little since this will return an error if you run it in a workbook that is not yet saved (ie there is no valid path to save the PDF at) or if the cell with the cell with the filename is empty.

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