我有以下代码。这让我想知道为什么工作簿代码中的 BeforePrint 事件被触发,即使我没有打印任何东西。工作簿绝对不是空白。错误在于创建PDF文件。
该文件可以很简单地将工作表保存为PDF格式,包括工作表的名称,工作簿的文件路径以及工作表中的一些详细信息。
我遗失的任何东西?我对VBA并不陌生,但今天这让我很烦恼。我在Windows 7旗舰版上使用MS Excel 2016。
编辑:我尝试删除以下代码,但问题仍然存在:
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
代码如下:
Option Explicit
Public Sub createpdffile()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim sheetname As String, sheetcode As String
Dim iRow As Long
Dim openPos As Integer
Dim closePos As Integer
'temporarily disable error handler so that I can see where the bug is.
'On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
wbA.Save
'get last row of sheet and set print area to last row with L column
iRow = wsA.Cells(Rows.Count, 1).End(xlUp).Row
wsA.PageSetup.PrintArea = wsA.Range("A1:L" & iRow).Address
'just checking name in sheet and removing needed characters
sheetname = wsA.Name
openPos = InStr(sheetname, "(")
closePos = InStr(sheetname, ")")
sheetcode = Mid(sheetname, openPos + 1, closePos - openPos - 1)
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'create default name for saving file
strFile = sheetcode & " No. " & wsA.Cells(11, 9) & " - " & wsA.Cells(8, 3) & ".pdf"
strPathFile = strPath & strFile
'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
'THIS IS WHERE THE ERROR IS LOCATED
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file" & vbNewLine & _
"Please complete the details needed!", vbOKOnly + vbExclamation, "Error Saving as PDF"
Resume exitHandler
End Sub
来自Foxfire and Burns and Burns'想法的解决方案:
我在主要分组之前添加了一个公开声明。
Option Explicit
'added line
Public myboolean as Boolean
Public Sub createpdffile()
myboolean = True
....
然后我在BeforePrint事件中添加了一行说:
If myboolean = True Then Exit Sub
现在,当调用虚拟PDF打印机时,它会绕过BeforePrint事件。
答案 0 :(得分:1)
wsA.ExportAsFixedFormat
该行激活BeforePrint事件。实际上,您正在打印PDF文件。它可用作虚拟PDF打印机。