如何使用命令按钮将Excel工作表另存为PDF?

时间:2017-12-06 17:22:42

标签: vba

我得到一个'语法错误',下面的R线下方的编码朝向下方。我试图将打开的工作表保存为引用单元格D3中的订单号的PDF文件。谢谢你的帮助!

Private Sub CommandButton1_Click()
Dim OrderDate As String, PONumber As String, Vendor As String, ShipTo As String, SKU As String, Path As String, filename As String
Dim R As Long, LastSKURow As Long, NextDBRow As Long, OFrm As Worksheet, DB As Worksheet
Set OFrm = Worksheets("Order Form 1")
Set DB = Worksheets("Database")
OrderDate = OFrm.Range("B3")
PONumber = OFrm.Range("D3")
Vendor = OFrm.Range("B7")
ShipTo = OFrm.Range("D7")
LastSKURow = OFrm.Cells(OFrm.Rows.Count, "F").End(xlUp).Row
For R = 3 To LastSKURow
    SKU = OFrm.Range("F" & R).Value
    NextDBRow = DB.Cells(DB.Rows.Count, "A").End(xlUp).Row + 1
    DB.Range("A" & NextDBRow).Value = OrderDate
    DB.Range("B" & NextDBRow).Value = PONumber
    DB.Range("C" & NextDBRow).Value = Vendor
    DB.Range("D" & NextDBRow).Value = ShipTo
    DB.Range("E" & NextDBRow).Value = SKU
Next R
Application.ScreenUpdating = False
OFrm.ExportAsFixedFormat Type:=xlTypePDF, _
        Path ="C:\PDF\"
        filename = OFrm.Range("D3")
        OpenAfterPublish = False
OFRrm.SaveAs filename:=Path & filename & ".pdf", FileFormat:=xlTypePDF
End Sub

2 个答案:

答案 0 :(得分:1)

SaveAs行是多余的。您只需要修复ExportAsFixedFormat即可正常工作。使用命名参数时,需要使用:=而不是just =。我建议为PDF保存创建一个新的Sub。

Sub SaveOrderAsPDF()
    Dim PDFName As String
    PDFName = Worksheets("Order Form 1").Range("D3").Value
    ChDir "C:\PDF"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\PDF\" & PDFName, Quality:=xlQualityStandard, IncludeDocProperties:= _
    True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub

有了这个工作,只需将SaveOrderAsPDF添加到现有的子。

答案 1 :(得分:0)

我认为您的变量“filename”与方法关键字“Filename”冲突。把你的变量叫做别的......

OFRrm.SaveAs Filename:= Path & myFile & ".pdf", FileFormat:=xlTypePDF

或者只是完全删除参数中的关键字:

OFRrm.SaveAs Path & myFile & ".pdf", xlTypePDF