我有这个代码,如果单元格包含特定文本,则拒绝并取消保存工作簿。代码工作正常,但如果我希望它拒绝保存,如果范围中的某些单元格包含特定的文本,那么它不起作用。我的代码在下面工作:
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
你们有什么想法吗?
答案 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个消息框...