如何检查是否填写了必填字段?

时间:2012-07-10 12:26:22

标签: excel vba

我想在保存文件之前检查我的工作表中的必填字段中的文本。如果单元格B50:B53具有文本,则相应的单元格D50:D53是强制性的。如果单元格B50:B53为空,则列D中的相应字段是可选的。

如果我将此规则应用于一行,则可以使用以下代码。但是,我想测试所有情况(B50和D50,B51和D51 ......)。如何在不复制代码4次的情况下执行此操作?

Dim MsgStr As String
Dim ws As Worksheet, r As Range, g As Range    

Set ws = wb.Sheets("Allotment hotel")
Set r = ws.Range("B50").Cells
Set g = ws.Range("D50").Cells

If r <> "" And g = "" Then
    MsgStr = "Room type was not found in the sheet 'Allotment hotel'"
End If

1 个答案:

答案 0 :(得分:1)

Sub check()

    Dim msg As String
    Dim rng As Range
    Set rng = Sheets("Allotment hotel").Range("B50:B53")

    For Each cell In rng
        If Not IsEmpty(cell) Then
            If IsEmpty(cell.Offset(0, 2)) Then
                msg = "Whatever String you want"
            End If
        End If
    Next cell

End Sub

或为单元格B50:B53创建命名范围,我们称之为checkrng

Set rng = Sheets("Allotment hotel").Range("checkrng")