首页 > 解决方案 > PDF 被保存两次而不是一次

问题描述

我想将我的 xls 文档另存为 PDF。
有些文件包括“自述文件”,有些则没有。
在这种情况下,我设置了导致强制保存的条件,尽管存在“自述文件”表。

我在这里找到了一些提示:测试或检查工作表是否存在

Sub sheet_exist()
 Dim I As Long
 For I = 1 To Worksheets.Count
  If Worksheets(I).Name = "Readme" Then
    Sheets("Readme").Visible = False

  ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    ThisWorkbook.Path & "\" & ThisWorkbook.Name, _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, OpenAfterPublish:=True

  Sheets("Readme").Visible = True
  Else
  ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    ThisWorkbook.Path & "\" & ThisWorkbook.Name, _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, OpenAfterPublish:=True
   End If
  Next I
 End Sub

我的 PDF 文档被保存了两次。我怎样才能消除第二次保存?

标签: excelvbapdf

解决方案


您的for/next循环当前的结构方式是每次迭代都会保存您的工作表(它将首先检查当前工作表是否为“自述文件”,然后保存工作簿 - 对于工作簿中的每个工作表)。因此,如果您的工作簿中有两张工作表,它将保存您的工作簿两次。

您需要重组代码,因此它首先检查“自述文件”是否存在,然后保存工作簿一次。

Sub sheet_exist()

    Dim I As Long
    Dim bReadmeExists As Boolean
    
    'First, we loop through all sheets and check if "Readme" exists. If it does, we hide the sheet.
    For I = 1 To Worksheets.Count
        If Worksheets(I).Name = "Readme" Then
            Sheets("Readme").Visible = False
            'If readme exists, we need to make it visible again in the end
            bReadmeExists = True
        End If
    Next I
            
    'Now we export the workbook once
    ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                     ThisWorkbook.Path & "\" & ThisWorkbook.Name, _
                                     Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                                     IgnorePrintAreas:=False, OpenAfterPublish:=True
    
    'Finally, we make the readme sheet visible again
    If bReadmeExists Then
        Sheets("Readme").Visible = True
    End If
    
End Sub

我还添加了一个布尔变量来“记住”自述文件是否存在(因此我们最终可以在导出后再次使其可见)。我还允许自己正确缩进代码,这样更容易阅读。


推荐阅读