仅在单元格值为真时打印

在打印之前,我已经设置了一个打印button来检查一个单元格是否有值,但是两个消息框都会popup,但是如果在消息框中select取消,表格仍然会打印。 如果点击取消,我怎样才能防止打印?

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 

提前感谢任何帮助约翰戴维斯

在我看来,这里有很多错误,这里有一些笔记和一个build议的改进:

 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 

你写了“vbCanel”而不是“vbCancel”。 当然,这从来不是“真实的”,所以你永远不会退出程序。