0

我想在保存文件之前检查我的工作表中必填字段中的文本。如果单元格 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
4

1 回答 1

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")
于 2012-07-10T12:37:28.087 回答