我需要一些关于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表中的样本。
感谢您的帮助!
答案 0 :(得分:2)
你很亲密!一对夫妇改变了:
您需要检查单元格的.DisplayFormat
,因为这是条件格式。
您在进入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
同样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