在microsoft excel上进行必需的字段验证

时间:2012-08-22 02:29:14

标签: excel excel-vba excel-2007 excel-2003 vba

我在excel(2003/2007)中有5列(SNO,姓名,电话,地址,Pin) Excel可以有“n”否。记录。
我想应用验证,这样,当我们保存excel表时,“SNO”(包含整数值)列的值永远不应为空,当任何一个(Name,Phone,Address,Pin)列具有值时。
如果不是这种情况,则应出现错误信息 我手动输入数据 我试过了:
编辑:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    If Worksheets("Sheet1").Range("SNO").Value = "" Then
        MsgBox "You must fill in SNO."
        Cancel = True
    End If
End Sub

我们可以在不编写代码的情况下应用验证吗?

1 个答案:

答案 0 :(得分:0)

据我所知,VBA是最好的(仅限?)方式。

尝试

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim rng As Range
    Dim rw As Range
    Dim dat As Variant

    ' change to your sheet name
    With Worksheets("Sheet4")
        ' Get data range to check
        ' Assumes SNO is column A and Name etc is Column B to E
        Set rng = .Range(.UsedRange.Columns(1), .UsedRange.Columns(5))
        For Each rw In rng.Rows
            ' If SNO cell is empty
            If rw.Cells(1, 1) = "" Then
                ' Check if other cells are not blank
                dat = Join(Application.Transpose(Application.Transpose(rw.Value)))
                If dat <> "" Then
                    MsgBox "You must fill in SNO."
                    Cancel = True
                    Exit For
                End If
            End If
        Next
    End With
End Sub