2017-03-03 85 views
2

所以我有這個簡單的小碼到一個Excel工作表上我的Excel表格轉換爲PDF上的命令按鈕:Excel以PDF問題

Sub Save_Excel_As_PDF() 

    ActiveSheet.ExportAsFixedFormat _ 
        Type:=xlTypePDF 

End Sub 

的問題是,我必須通過步驟手動先走(另存爲,然後是PDF等),以便按鈕在首先經過手動步驟後工作。

我想保存這個地方,只需點擊按鈕來創建PDF,而無需先執行所有初始手動步驟。這個代碼可以修改來做到這一點嗎?

+0

當我運行'ActiveSheet.ExportAsFixedFormat xlTypePDF'時,我不提示手動執行任何操作。我不知道輸出*在哪裏*,但我沒有得到任何錯誤或警告或任何中斷運行時。什麼,你特別想要做什麼? –

回答

3

如果不指定FileName參數,該PDF將在您的Documents文件夾中保存。在某個文件夾中執行手動Save As之後,下次它將在同一個文件夾中創建。

你不需要這在所有的,你可以創建在同一文件夾作爲您的工作簿文件,具有相同的名稱作爲工作表的名稱,通過指定FileName參數:

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ 
    FileName:=ThisWorkbook.Path & "\" & ActiveSheet.name 

您可以指定其他名稱或除ThisWorkbook.Path以外的其他文件夾。

+1

真棒!謝謝! – Lucho

+0

@Lucho歡迎您:) –

1

猜猜這對我的作品:

Sub Macro1() 

ChDir "C:\Users\Shyamsundar.Shankar\Desktop" 
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Users\Shyamsundar.Shankar\Desktop\Sheet1.pdf", Quality:=xlQualityStandard 

End Sub 
0

以下腳本會將所有Excel文件轉換爲PDF文件。

Sub Convert_Excel_To_PDF() 

    Dim MyPath As String, FilesInPath As String 
    Dim MyFiles() As String, Fnum As Long 
    Dim mybook As Workbook 
    Dim CalcMode As Long 
    Dim sh As Worksheet 
    Dim ErrorYes As Boolean 
    Dim LPosition As Integer 

    'Fill in the path\folder where the Excel files are 
    MyPath = "c:\Users\yourpath_here\" 

    FilesInPath = Dir(MyPath & "*.xl*") 
    If FilesInPath = "" Then 
     MsgBox "No files found" 
     Exit Sub 
    End If 

    Fnum = 0 
    Do While FilesInPath <> "" 
     Fnum = Fnum + 1 
     ReDim Preserve MyFiles(1 To Fnum) 
     MyFiles(Fnum) = FilesInPath 
     FilesInPath = Dir() 
    Loop 

    With Application 
     CalcMode = .Calculation 
     .Calculation = xlCalculationManual 
     .ScreenUpdating = False 
     .EnableEvents = False 
    End With 

    If Fnum > 0 Then 
     For Fnum = LBound(MyFiles) To UBound(MyFiles) 
      Set mybook = Nothing 
      On Error Resume Next 
      Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum)) 
      On Error GoTo 0 

      If Not mybook Is Nothing Then 

       LPosition = InStr(1, mybook.Name, ".") - 1 
       mybookname = Left(mybook.Name, LPosition) 
       mybook.Activate 

       'All PDF Files get saved in the directory below: 
       ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= 
        "C:\Users\your_path_here\" & mybookname & ".pdf", 
        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _ 
        :=False, OpenAfterPublish:=False 

      End If 

      mybook.Close SaveChanges:=False 

     Next Fnum 
    End If 

    If ErrorYes = True Then 
     MsgBox "There are problems in one or more files, possible problem:" _ 
      & vbNewLine & "protected workbook/sheet or a sheet/range that not exist" 
    End If 

    With Application 
     .ScreenUpdating = True 
     .EnableEvents = True 
     .Calculation = CalcMode 
    End With 

End Sub