仅在单元格值为true时打印

时间:2015-03-19 10:46:38

标签: excel vba

我已经设置了一个打印按钮,用于在打印前检查单元格是否有值,但是两个消息框都会弹出,但如果我在消息框中选择取消,则表单仍会打印。如果单击取消,如何防止打印。

Private Sub CommandButtonPrint_Click()
If Sheets("New").Range("email").Value <> "" 
Cancel = True
MsgBox "Email Address Needs to be Completed", vbInformation
If response = vbCancel Then Exit Sub
Application.EnableEvents = True
response = MsgBox("Do you really want to print?", vbOKCancel)
If response = vbCanel Then Exit Sub
Sheets("New").PrintOut copies:=1, Collate:=True
End If
End Sub

提前感谢您的帮助 约翰戴维斯

2 个答案:

答案 0 :(得分:1)

你写了&#34; vbCanel&#34;而不是&#34; vbCancel&#34;。当然,这绝不是&#34; True&#34;所以你永远不会退出这个程序。

答案 1 :(得分:0)

我认为这里出现了很多问题,这里有一些注释和建议的改进:

Private Sub CommandButtonPrint_Click()
If Sheets("New").Range("email").Value <> "" '// requires a "Then" keyword
Cancel = True   '// Cancel isn't declared as a variable, why is this here?
MsgBox "Email Address Needs to be Completed", vbInformation
If response = vbCancel Then Exit Sub '// response hasn't been assigned a value yet so will be empty
Application.EnableEvents = True '// No events are fired at this point so not sure why this is here
response = MsgBox("Do you really want to print?", vbOKCancel)
If response = vbCanel Then Exit Sub '// typo - should be "vbCancel"
Sheets("New").PrintOut copies:=1, Collate:=True
End If '// End If without valid If block.
End Sub

您还应该尝试缩进语句以使代码更易于阅读,这在查找和修复错误时会产生很大的帮助。以下是我认为此代码应如下所示的示例:

Private Sub CommandButtonPrint_Click()

    If Sheets("New").Range("email").Value = "" Then MsgBox "Email Address Needs to be Completed", vbInformation

    If MsgBox("Do you really want to print?", vbOKCancel) = vbOK Then Sheets("New").PrintOut copies:=1, Collate:=True

End Sub