我有一个场景,我必须检查列A是否为空,其他列中相应的行值不应为空。如果是,我想要抛出一条错误消息。
所以我想出了这个。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
Dim rngCell As Range
Dim lngLstRow As Long, lngTCols As Long
Dim lngRowCheck(1 To 5) As String
For Each rngCell In Range("A1:A" & lngLstRow)
If Not IsEmpty(rngCell.Value) Then
lngRowCheck(1) = "C"
lngRowCheck(2) = "F"
lngRowCheck(3) = "G"
lngRowCheck(4) = "J"
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For i = 1 To UBound(lngRowCheck)
For Each rngCell In Range(lngRowCheck(i) & "2:" & lngRowCheck(i) & lngLstRow)
If rngCell.Value = 0 Then
MsgBox ("Please enter a name in cell " & rngCell.Address)
rngCell.Select
End If
Next
Next i
Next
End Sub
然而,这并不起作用,并且在每次保存之前都没有进行验证,我也无法对其进行调试。有帮助吗?难道我做错了什么?
答案 0 :(得分:1)
尝试这样的事情......
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
Dim rngCell As Range, cell As Range
Dim lngLstRow As Long, lngTCols As Long
Dim lngRowCheck(1 To 5) As String
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For Each rngCell In Range("A1:A" & lngLstRow)
If Not IsEmpty(rngCell.Value) Then
lngRowCheck(1) = "C"
lngRowCheck(2) = "F"
lngRowCheck(3) = "G"
lngRowCheck(4) = "J"
For i = 1 To UBound(lngRowCheck)
For Each cell In Range(lngRowCheck(i) & "2:" & lngRowCheck(i) & lngLstRow)
If cell.Value = 0 Then
MsgBox "Please enter a name in cell " & cell.Address(0, 0)
cell.Select
Cancel = True
Exit Sub
End If
Next cell
Next i
End If
Next rngCell
End Sub