我有一个 VBA 宏,它可以获取电子表格中的某个范围并将其转换为 PDF。或者至少,应该如此!我正在 Microsoft 365 企业应用版的 Excel 中运行 VBA 7.1。
这是有问题的子例程:
Sub rangeToPdf(printRange As String, strFilename As String, strTitle As String)
Dim topMarginInches As Single
topMarginInches = 0.6
If (InStr(strTitle, vbLf) > 0) Then
' Title goes over a single line, so need to bump the margins to make space
topMarginInches = 1
End If
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = strTitle
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0.3)
.RightMargin = Application.InchesToPoints(0.3)
.TopMargin = Application.InchesToPoints(topMarginInches)
.BottomMargin = Application.InchesToPoints(0.6)
.HeaderMargin = Application.InchesToPoints(0.3)
.FooterMargin = Application.InchesToPoints(0.3)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = True
.CenterVertically = False
.Orientation = xlPortrait
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = 100
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
.EvenPage.LeftHeader.Text = ""
.EvenPage.CenterHeader.Text = ""
.EvenPage.RightHeader.Text = ""
.EvenPage.LeftFooter.Text = ""
.EvenPage.CenterFooter.Text = ""
.EvenPage.RightFooter.Text = ""
.FirstPage.LeftHeader.Text = ""
.FirstPage.CenterHeader.Text = ""
.FirstPage.RightHeader.Text = ""
.FirstPage.LeftFooter.Text = ""
.FirstPage.CenterFooter.Text = ""
.FirstPage.RightFooter.Text = ""
End With
Application.PrintCommunication = True
' Prints the specified range to a PDF with the selected filename.
Range(printRange).ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFilename
End Sub
不幸的是,当我在计算机上运行它时,它始终失败!我已经在调试器中单步执行了它,我可以看到我们运行了
Range(printRange).ExportAsFixedFormat
命令,但它似乎是一个无操作!什么也没发生,我们继续下一行。这让我感到困惑,因为我预计如果出现正常错误(例如,目录不存在,或只读,或类似性质的目录),将会弹出某种错误。我已经做了检查,看看是否有任何方法可以进行一些错误处理来捕获异常,但我看不到任何东西。
我已经看到这个确切的宏在同事的电脑上运行良好,但由于某种原因它在我的电脑上无法运行!有谁知道什么可能会导致这个问题?
我最终弄清楚了这里发生的事情 - 感谢 @CDP1082 的建议,看看当我尝试手动导出时会发生什么。事实证明,敏感度标签设置为
Confidential
,这意味着当我尝试导出为 PDF 时,出现一条错误消息,指示该文件“尚未使用新的敏感度级别保存”。我尝试减少文档上的敏感度标签,此时我可以毫无问题地运行我的导出宏!
这不是一个理想的答案 - 从长远来看,您希望这些敏感度标签保持正确和一致。但短期内,我可以运行宏来生成我需要的 PDF,然后根据需要将敏感度切换回机密。
感谢大家的帮助!