【问题标题】:PDF is saved twice rather than oncePDF 被保存两次而不是一次
【发布时间】:2020-07-30 11:11:43
【问题描述】:

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

我在这里找到了一些提示:Test or check if sheet exists

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 文档被保存了两次。如何消除第二次保存?

【问题讨论】:

    标签: excel vba pdf


    【解决方案1】:

    您的 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
    

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

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      相关资源
      最近更新 更多