0

Excel シートにフォームがあり、2 つの必須セルがあり、ユーザーが未完成のままにすることがよくあります。セルが完成していない場合、ユーザーがシートを保存できず、赤で強調表示され、メッセージボックスが表示される次のコードがあります。

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

ok As Boolean
Dim xlSht As Worksheet
OK = False

Set xlSht = ThisWorkbook.Worksheets("Changes Form")

'Cell 1
If xlSht.Range("B13") = "" Then
    xlSht.Range("B13").Interior.Color = RGB(255, 0, 0)
    ok = True
Else
    xlSht.Range("B13").Interior.ColorIndex = xlNone
    ok = False

If xlSht.Range("E13") = "" Then
    xlSht.Range("E13").Interior.Color = RGB(255, 0, 0)
    ok = True
Else
    xlSht.Range("E13").Interior.ColorIndex = xlNone
    ok = False

End If

End If

If OK = True Then
MsgBox "Please review the highlighted cells and ensure the fields are populated."
Cancel = True
End If

End Sub

コードは機能しますが、両方のセルにエントリがない場合、セル B13 のみに色が付けられます。コードの「ok = True」ビットが B13 に対して実行されると、残りのコードを最後までスキップすると思います。両方のセルが強調表示されるように修正する方法がわかりません。

データ検証を通じてユーザーに警告することを考えましたが、両方のセルにリストボックスがあるため、まだ可能かどうかわかりません。

助けてくれてありがとう。

4

1 に答える 1

1

コードを以下に置き換えます。最初の値が空の場合、2 番目のロジックがありません。また、値がある場合は false にする必要はありません。私が最後に変更したのは、cellsNotPopulated への「OK」ブール値だったので、より読みやすくなりました。

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

Dim xlSht As Worksheet
Dim cellsNotPopulated As Boolean
cellsNotPopulated = False

Set xlSht = ThisWorkbook.Worksheets("Changes Form")

    With xlSht

        If .Range("B13") = "" Then
            .Range("B13").Interior.Color = RGB(255, 0, 0)
            cellsNotPopulated = True
        Else
            .Range("B13").Interior.ColorIndex = xlNone
        End If

        If .Range("E13") = "" Then
            .Range("E13").Interior.Color = RGB(255, 0, 0)
            cellsNotPopulated = True
        Else
            .Range("E13").Interior.ColorIndex = xlNone
        End If

    End With

    If cellsNotPopulated = True Then
        MsgBox "Please review the highlighted cells and ensure the fields are populated."
        Cancel = True
    End If

End Sub
于 2012-11-23T13:12:20.043 に答える