首页 > 解决方案 > 导出数组中指定的工作表以分隔 pdf

问题描述

我正在尝试将数组中指定的工作表导出为单独的 pdf。
我的代码没有查看指定的数组。

Sub ExportToPDFs()
   
    Dim outFldr As String
    Dim ws As Worksheet
    Dim i As Variant, sheets_to_select As Variant

    outFldr = ActiveWorkbook.Path
    sheets_to_select = (Array(2, 3, 4, 5, 6, 7, 8))

    For Each i In sheets_to_select
        ThisWorkbook.Sheets(i).ExportAsFixedFormat Type:=xlTypePDF, _
          Filename:=outFldr & "\" & i & ".pdf", _
          Quality:=xlQualityStandard, IncludeDocProperties:=True, _
          IgnorePrintAreas:=False, OpenAfterPublish:=False

    Next i

End Sub

标签: arraysexcelvbaloopspdf

解决方案


我将命名变量的代码重构为更具可读性

并修复了几件事

  • 您将项目分配给数组的方式
  • 循环(for)

代码:

Sub ExportToPDFs()
   
   Dim outputFolderPath As String
   Dim currentWorksheet As Worksheet
   Dim counter As Long
   Dim sheetsIndexArr As Variant
   
   ' Define the folder path
   outputFolderPath = ActiveWorkbook.Path ' Check if this could be ThisWorkbook
   
   ' Define the indexes of sheets to be exported
   sheetsIndexArr = Array(2, 3, 4, 5, 6, 7, 8)
   
   For counter = LBound(sheetsIndexArr) To UBound(sheetsIndexArr)
   
      ThisWorkbook.Sheets(counter).ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:=outputFolderPath & "\" & counter & ".pdf", _
            Quality:=xlQualityStandard, IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, OpenAfterPublish:=False
   
   
   Next counter

End Sub

让我知道它是否有效


推荐阅读