问题
I searched the site and could not find an answer for this.
Background: I have this Macro as a button on a worksheet. It works well for what I need:
Sub FactSheetSaveToPDF()
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\" & Range("b2") & " - " & Month(Date) & "." & Day(Date) & "." & Year(Date) & "." _
& Hour(Time) & Minute(Time) & Second(Time) & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
What I need to do now is make it so that a user can ONLY print using these buttons, for compliance reasons. So, whether normal printing is disabled, blocked, whatever, a user of this excel document should only be able to print a worksheet if they hit the button to print to PDF. There cannot be an ability for someone to print outside of this macro button. CTRL+P, file-print, all not allowed.
I saw one answer that disabled all printing, including from the macro. This will not work. The Print-to-PDF macro button needs to work.
I saw another answer that disabled all printing from all excels that the user may have open; this is too much power for one man. I only want to disable printing from this particular excel document.
I assume I will have to create some code that disables all printing, and then amend the macro for the print button to be an exception, or some variation of that.
If you haven't noticed by my vernacular, I am a beginner, if that, at VBA. Trying to keep it as simple as possible. I greatly appreciate any help.
回答1:
Easy. Use this in the workbook code area:
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Cancel = True
End Sub
This will stop the User, but in your button code:
Sub FactSheetSaveToPDF()
Application.EnableEvents = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\" & Range("b2") & " - " & Month(Date) & "." & Day(Date) & "." & Year(Date) & "." _
& Hour(Time) & Minute(Time) & Second(Time) & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
Application.EnableEvents = True
End Sub
来源:https://stackoverflow.com/questions/37465969/how-can-i-disable-printing-an-excel-workbook-except-when-using-a-print-to-pdf-ma