如果单元格包含文本,请拒绝保存

时间:2016-05-18 11:06:23

标签: excel excel-vba vba

我有这个代码,如果单元格包含特定文本,则拒绝并取消保存工作簿。代码工作正常,但如果我希望它拒绝保存,如果范围中的某些单元格包含特定的文本,那么它不起作用。我的代码在下面工作:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Sheets("Sheet1").Range("A1").Value = "Fill in a comment" Then
    Cancel = True
    Response = MsgBox("Fill in a comment", vbCritical, "Error!")
End If

End Sub

我尝试使其工作但不是

的代码
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean

 For Each c In Sheet1.Range("A1:A5000")
        If c.Value = "Fill in a comment" Then
             Cancel = True
              Response = MsgBox("Fill in a comment", vbCritical, "Error!")
        End If
    Next
End Sub
你们有什么想法吗?

1 个答案:

答案 0 :(得分:1)

请尝试而不是循环:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    Cancel = Not Sheet1.Range("A1:A5000").Find("Fill in a comment") Is Nothing
    If Cancel Then MsgBox "Fill in a comment", vbCritical, "Error!"

End Sub

它使用.Find()方法查找"Fill in a comment",如果不是Nothing,则Cancel设置为True

然后,我们测试Cancel的值,看看是否需要显示消息框。

这样做也可以确保如果您在该范围内的500个不同单元格中写入"Fill in a comment",则不会获得500个消息框...