excel - 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 文档被保存了两次。我怎样才能消除第二次保存?
解决方案
您的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
我还添加了一个布尔变量来“记住”自述文件是否存在(因此我们最终可以在导出后再次使其可见)。我还允许自己正确缩进代码,这样更容易阅读。
推荐阅读
- r - 在数据框中将两列绑定在一起
- rust - 为什么 deref coersion 对嵌套的 Vec 不起作用?
- java - ESP8266 滞后一段时间,然后更新非常快
- c# - ASP.NET MVC:一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性
- javascript - 为什么 $('div :not(script)').contents().filter(function() 会导致转义的 HTML 字符变为未转义?
- python - 在 opencv 回调函数之外访问变量
- typescript - 预先不知道属性名称的打字稿类
- visual-studio-2019 - 调试时如何使 Visual Studio 2019 在 try 语句中不中断?
- python - IndexError:数组的索引过多:数组是 0 维的,但有 1 个被索引
- c++ - 输入7个字母单词,输出7位电话号码