结合BeforeSave事件的标准

时间:2018-04-20 15:27:12

标签: excel vba excel-vba conditional-formatting

我需要一些关于BeforeSave VBA事件的帮助。

我已经引入了一个额外的标准,使用条件格式来突出显示一个单元格,如果它不等于10个字符。

问题是,我已经在VBA中有一个BeforeSave事件来检查是否选中了复选框,如何组合这两个语句以便在保存之前检查这两个条件?

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

Application.ScreenUpdating = False

Cancel = Not Worksheets(1).CheckBoxes(1).Value = 1

Dim rng As Range

For Each rng In Worksheets(1).UsedRange
    If rng.DisplayFormat.Interior.Color = vbRed Then
        MsgBox ("Please correct any fields highlighted in red")
    Exit For
    End If
Next rng

Application.ScreenUpdating = True

If Cancel Then MsgBox "Please accept the terms and conditions before saving the Invoice"

End Sub

突出显示的标准是我用来评估复选框的标准,其间是代码我试图检查任何填充红色的单元格。也是excel表中的样本。 enter image description here

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

你很亲密!一对夫妇改变了:

  1. 您需要检查单元格的.DisplayFormat,因为这是条件格式。

  2. 您在进入If条件之前退出了子程序。请改用Exit For

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    
    Application.ScreenUpdating = False
    
    Cancel = Not Worksheets(1).CheckBoxes(1).Value = 1
    
    Dim rng As Range
    
    For Each rng In ActiveSheet.UsedRange
        If rng.DisplayFormat.Interior.Color = vbRed Then
            Cancel = True
        Exit For
        End If
    Next rng
    
    Application.ScreenUpdating = True
    
    If Cancel Then MsgBox "Please accept the terms and conditions"
    
    End Sub
    
  3. 同样Application.ScreenUpdating = True需要在你的循环之外,否则它可能永远不会被重新开启!

    更新:

    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    
    Application.ScreenUpdating = False
    
    Cancel = Not Worksheets(1).CheckBoxes(1).Value = 1
    
    Dim rng As Range
    
    For Each rng In Worksheets(1).UsedRange
        If rng.DisplayFormat.Interior.Color = vbRed Then
            MsgBox ("Please correct any fields highlighted in red")
            Cancel = True
            Application.ScreenUpdating = True
            Exit Sub
        End If
    Next rng
    
    Application.ScreenUpdating = True
    
    If Cancel Then MsgBox "Please accept the terms and conditions before saving the Invoice"
    
    End Sub
    
相关问题