Excel VBA从值为TRUE的列表中选择工作表

时间:2018-05-04 16:04:27

标签: excel vba excel-vba

我正在尝试编写一个将某些工作表打印到pdf的宏。我有一个工作表(" PDF")列出了D列中工作簿中的所有工作表,然后是F列中的工作表,我有一个TRUE / FALSE值列表。我的宏应该将D列中F列中为TRUE的所有工作表打印到单个pdf文件中。

此工作簿中的工作表数确实有所不同。

以下是我第一次尝试此代码

Sub PDFCreater()

Dim pdfName As String
Dim FullName As String
Dim myArray() As Variant
Dim ArrSize As Integer
Dim ArrWkst As String
Dim RowCnt As Long, ArrCnt As Long

pdfName = Sheets("PDF").Range("D1").Text
FullName = ThisWorkbook.Path & "\" & pdfName & ".pdf"

ReDim myArray(Sheets("PDF").Range("D2").Value)    'Size of array/ number of sheets in PDF
ArrCnt = 0
For RowCnt = 8 To 302
    If Sheets("PDF").Cells(RowCnt, 6).Value = True Then
        myArray(ArrCnt) = Cells(RowCnt, 4).Value
        ArrCnt = ArrCnt + 1
    End If
    RowCnt = RowCnt + 1
Next
'Select all worksheets in MyArray()
Sheets(myArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FullName _
, Quality:=xlQualityMedium, IncludeDocProperties:=False,
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

2 个答案:

答案 0 :(得分:1)

根据您的说明,您的代码中有几处错误

Sub Test()
Dim pdfName As String
Dim FullName As String
Dim myArray() As Variant
Dim ArrSize As Integer
Dim ArrWkst As String
Dim RowCnt As Long, ArrCnt As Long

    pdfName = Sheets("PDF").Range("D1").Text
    FullName = ThisWorkbook.Path & "\" & pdfName & ".pdf"

    ' You need to re-dim the array in the loop in order to have an array with
    ' the correct dimension. Otherwisae the array is too big and will contain
    ' empty entries
    'ReDim myArray(Sheets("PDF").Range("D2").Value)    'Size of array/ number of sheets in PDF
    ArrCnt = 0
    For RowCnt = 8 To 302
        If Sheets("PDF").Cells(RowCnt, 6).Value Then
            ReDim Preserve myArray(ArrCnt)
            myArray(ArrCnt) = Cells(RowCnt, 4).Value
            ArrCnt = ArrCnt + 1
        End If
        ' the for loop will increase rowcnt itself
        ' no need to do that
        'RowCnt = RowCnt + 1
    Next
    'Select all worksheets in MyArray()
    Sheets(myArray).Select
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FullName, _
                                    IncludeDocProperties:=False, _
                                    IgnorePrintAreas:=False, OpenAfterPublish:=True

End Sub

答案 1 :(得分:0)

使用循环隐藏具有FALSE值的表格,然后:

ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FullName _
        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
        :=False, OpenAfterPublish:=True

这将把整个工作簿保存为PDF,但隐藏的工作表除外。