数据验证例程不起作用

时间:2015-02-02 21:16:59

标签: excel vba excel-vba event-handling

我有这个宏来检查从A单元格到I的空白。如果单元格是空白的,则用户无法保存。但问题是,如果我不在A单元格中输入任何内容,则启用保存。

这是我的VBA代码:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim rsave As Range, N As Long
    Dim cell As Range
    With Sheet2
        N = Cells(Rows.Count, "A").End(xlUp).Row
        For i = 1 To N
            Set rsave = Range("A" & i & ":I" & i)
            For Each cell In rsave
                If cell = "" Then
                    Dim missdata
                    missdata = MsgBox("missing data", vbOKOnly, "Missing Data")
                    Cancel = True
                    cell.Select
                    Exit Sub
                End If
            Next cell
        Next i
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

我认为您应该正确引用您正在处理的对象 例如,您在此行中使用With Statement,但下一行并未真正引用Sheet2

With Sheet2
    N = Cells(Rows.Count, "A").End(xlUp).Row

要正确引用属性和对象,请在其前面添加dot,如:

With Sheet2
    N = .Cells(.Rows.Count, "A").End(xlUp).Row 'notice the dot before Cells

这一行也是如此:Set rsave = Range("A" & i & ":I" & i)
它应该是:

Set rsave = .Range("A" & i & ":I" & i) 'notice the dot

现在,您可以使用一个嵌套循环,而不是执行嵌套循环。
另外,引用相对于整列的最后一行。请尝试以下代码:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim rsave As Range, N As Long
    Dim cell As Range
    With Sheet2
        N = .Range("A:I").Find("*", [A1], , , xlByRows, xlPrevious).Row
        Set rsave = .Range("A1:I" & N)
        For Each cell In rsave
            If cell = "" Then
                MsgBox "Missing data.", vbOKOnly, "Missing Data"
                Cancel = True
                cell.Select
                Exit Sub
            End If
        Next cell
    End With
End Sub

你看,cell变量从左到右迭代,向上 所以它检查A1,B1,C1 ......等A2,B2,C2 ...... HTH。