简体   繁体   中英

How to generate PDF from specific sheet based on cell value?

I am trying to generate a single PDF from a single sheet (within one workbook) based on if that sheet has a 1 in A1. Only one of the 10 hidden sheets will ever have a 1 in A1 depending on what is filled in on the front sheet ("Calculator" / "Sheet1").

The code I have does generate the PDF but doesn't change the active sheet, so rather than jumping to the instance of the sheet with 1 in A1 it prints the sheet I was last on.

Sub GenPDF_OTJ()
    
    Dim saveInFolder As String
    Dim replaceSelected As Boolean
    Dim wsName As Variant
    Dim iVis As XlSheetVisibility
            
        
    saveInFolder = "C:\Downloads\pdf\"
    If Right(saveInFolder, 1) <> "\" Then saveInFolder = saveInFolder & "\"
        
        With ThisWorkbook
    
            replaceSelected = True
            For Each wsName In Array("OTJ Bus Admin", "OTJ SFSCA", "OTJ Sales L4") 'additional sheets to be added in once working
                If .Worksheets(wsName).Range("A1").Value > 0 Then 'A1 will only be 1 or 0
                    .Worksheets(wsName).Select replaceSelected
                    replaceSelected = False
                End If
            Next
                
            .ActiveSheet.Select
            With .ActiveSheet
            iVis = .Visible
                    .Visible = xlSheetVisible
            .ExportAsFixedFormat Type:=xlTypePDF, _
                                 Filename:=PdfFile, _
                                 Quality:=xlQualityStandard, _
                                 IncludeDocProperties:=True, _
                                 IgnorePrintAreas:=False, _
                                 OpenAfterPublish:=True
            .Visible = iVis
            .Visible = xlSheetHidden
        
        End With
    End With
        
End Sub

To make the answer more complete, I refactored your code (open to improvements though)

Read the comments and adjust it to fit your needs

Option Explicit

Public Sub GenPDF_OTJ()            
        
    '''''''''' Adjust values below ''''''''''

    ' Define folder to save in
    Dim saveInFolder As String
    saveInFolder = "C:\Temp\"
    
    ' Define output file name
    Dim outputFileName As String
    outputFileName = "Test.pdf" ' Include extension
    
    ' Define sheets to print list (array)
    Dim sheetsToPrintNames As Variant
    sheetsToPrintNames = Array("OTJ Bus Admin", _
                                "OTJ SFSCA", _
                                "OTJ Sales L4")
    
    
    ' Define cell address to check in each sheet
    Dim cellAddressToCheck As String
    cellAddressToCheck = "A1"
    
    ' Define cell value to check (if true, prints the sheet)
    Dim cellValueToPrint As Long ' Use Long if is an integer number or decimal or double search in google for vba variable types)
    cellValueToPrint = 1
    
    '''''''''' Adjust values above ''''''''''
    
    
    
    '''''''''' Code logic below ''''''''''
    
    ' Add backslash if it's missing
    If Right(saveInFolder, 1) <> "\" Then saveInFolder = saveInFolder & "\"
    
    
    ' Define target workbook
    Dim targetWorkbook As Workbook
    Set targetWorkbook = ThisWorkbook ' You could change this to Workbooks("SomeOtherWorkbookName")
    
    ' Review each sheet and print to pdf if condition is met
    Dim targetSheet As Worksheet
    For Each targetSheet In targetWorkbook.Worksheets
        
        ' If condition is met, then print sheet
        If targetSheet.Range(cellAddressToCheck).Value = cellValueToPrint Then
            
            ' Build output file path
            Dim outputFilePath As String
            outputFilePath = saveInFolder & outputFileName
            
            ' Check if target file exists
            If Len(Dir(outputFilePath)) <> 0 Then
            
                ' Check if target file is locked
                If IsFileOpen(outputFilePath) = True Then
                    MsgBox "Output file is locked, close it and retry (cancelling process)"
                    Exit Sub
                End If
                
            End If
            ' Get target sheet visibility
            Dim targetSheetVisibility As XlSheetVisibility
            targetSheetVisibility = targetSheet.Visible
            
            ' Force sheet to be visible
            targetSheet.Visible = xlSheetVisible
            
            targetSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                 FileName:=outputFilePath, _
                                 Quality:=xlQualityStandard, _
                                 IncludeDocProperties:=True, _
                                 IgnorePrintAreas:=False, _
                                 OpenAfterPublish:=True
                                 
            ' Return sheet visibility to previous state
            targetSheet.Visible = targetSheetVisibility
            
        End If
        
    Next targetSheet
        
        
End Sub

' Credits to Siddhart https://stackoverflow.com/a/25715352/1521579
Private Function IsFileOpen(ByVal FileName As String) As Boolean
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsFileOpen = False
    Case 70:   IsFileOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Note: One thing that I found was that you didn0t define the output file's name, so I set it with a variable (fixed). If you need to something like the sheet's name, code needs a minor tweek

Let me know if it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM