簡體   English   中英

Excel VBA:將 excel 工作表動態保存到一個 ZBCD1B68617759B1DFCFF110403A6B5A8 工作表中的工作表中(基於某些條件)

[英]Excel VBA: dynamically saving excel sheets into one PDF based on certain criteria in the cell (1 number = 1 sheet)

我得到了不同張數和相同結構的WB等等。 有一個字段,例如 D8,其中寫入數字 3 (CH),根據該單元格中的數字,我想將該數量的工作表准確導出到一個 PDF 中。 所以,如果寫成五頁,則將五頁寫入一頁 PDF ......或者如果是一頁,則寫入 PDF 中的一頁。 D8 中的該單元格將始終位於同一 position 上,但數量可能不同。 是否可以以某種方式將其寫入代碼以查看該數字並將那么多工作表導出到一個 PDF 中?

而且我想有一個選項來保存每個新的 PDF,不像現在自動創建的那樣,首先是文件夾,然后是文件。

這是我的WB的SS: 在此處輸入圖像描述

這是我正在使用的一段代碼,但只是為了將工作表保存到單個 PDF 中,我在 VBA 中不太好,所以任何幫助都會很棒!

Sub ExportAsPDF()

  Dim FolderPath As String

  FolderPath = "C:\Users\XYZ\Desktop\PDFs"
  MkDir FolderPath
  
  Sheets(Array("CH1", "CH2", "CH3")).Select
  ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & "\PDf", _
  openafterpublish:=False, ignoreprintareas:=False

  MsgBox "All PDF's have been exported!"
  End Sub

當您提出問題時,建議經常檢查並嘗試澄清要求澄清的評論......

如果我理解你的問題,請測試下一個代碼。 它假設我在評論中的假設的答案是肯定的。 該代碼提供了一個瀏覽 window 到 select 的文件夾,其中導出所選的( sheetsNo )張數:

Sub ExportAsPDF()
  Dim FolderPath As String, sheetsNo As Long, sh As Worksheet, arrSheets
  Dim fldr As FileDialog, sItem As String, fileName As String, i As Long
 
  sheetsNo = ActiveCell.value 'use there the sheet you need

  ReDim arrSheets(sheetsNo - 1) 'redim the array to keep the sheets
  
  'use a dialog to select the folder to export
  Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
  With fldr
    .Title = "Select a Folder where to export the pdf file"
    .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
 End With
NextCode:
 If sItem = "" Then Exit Sub 'if no folder selected the code stops
 
 FolderPath = sItem
  
  fileName = Replace(ThisWorkbook.Name, ".xlsm", ".pdf") 'use the workbook name, but changing its extension
  For i = 1 To sheetsNo
    arrSheets(i - 1) = Worksheets(i).Name 'put the sheets in an array
  Next

  Sheets(arrSheets).Select
  ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:=FolderPath & "/" & fileName, _
  openafterpublish:=False, ignoreprintareas:=False

  MsgBox "All PDF's have been exported!"
End Sub

請測試它並發送一些反饋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM