用户在VBA中命中保存时如何引发错误

时间:2016-07-06 14:49:59

标签: excel vba excel-vba

在我的A栏中,我有一个选项,让用户选择“是”或“否”。两种选择都有一个必需的单元格。

Example:
If User selects "YES"
 Mandatory cells will be in Colum A, D and E
If User selects "No"
 Mandatory cells will be in Colum B, C and G

让我们说在第1行,用户选择“是”并在A1和E1上输入一个值,但他忘了在单元格D1中添加值。 在第2行中,用户选择“否”并在B2和C2上输入值,忘记在单元格G2上输入值。

当他点击保存时,我想抛出一个错误,说“输入以下单元格的值.D1,G2

我的代码如下:

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

    Dim Target As Range
    If Not Intersect(Target, Range("A:A")) Is Nothing Then

                If Target = "YES" Then

                     For i = 1 To 15
                        If Target.Offset(0, i).Value = "" Then
                         MsgBox "Enter values on the mandatory cells (green)", vbCritical, ""
                        End If
                     Next i
                        Cancel = True

                ElseIf Target = "NO" Then
                    For i = 16 To 30
                         If Target.Offset(0, i).Value = "" Then
                          MsgBox "Enter values on the mandatory cells (green)", vbCritical, ""
                        End If
                    Next i
                    Cancel = True
                End If
         End If
End Sub

2 个答案:

答案 0 :(得分:2)

使用工作簿beforeSave事件并相应处理:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _ 
        Cancel as Boolean) 
   'your code here
End Sub

编辑OP的新代码:

你从未在你的代码中定义了什么,因此,交叉方法将始终不返回任何内容(如果它甚至可以正常工作)。我认为你混淆了Worksheet_change方法(包括" Target"范围)和Save。您必须定义BeforeSave方法运行时Target的内容。我建议在特定值范围内运行循环并检查是否满足所有所需条件。如果有些不符合要求,那么您可以为用户显示一条消息,指出他们缺少数据并阻止保存。

答案 1 :(得分:1)

尝试使用这两行中的一行。抛出这样的错误不是一个好主意,但如果你想要这么多...... 这是一个消息框:

msgbox "Enter a value of the following cells. D1 G2"

这是一个错误:

err.Raise 1, description:= "Enter a value of the following cells. D1 G2"