我有一张excel表,想要在保存之前制作一些单元格并将其发回给我们。
我有以下代码,但检查不会在指定的单元格上停止并继续。我应该怎么做才能让它停在指定的范围内?
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 2) As String
lngRowCheck(1) = "B2:B18"
lngRowCheck(2) = "D2:D4"
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
Exit Sub
End If
Next
Next i
End Sub
答案 0 :(得分:2)
您可以使用Application.Union
合并搜索范围,您可以取出For
循环,您的代码将更清晰,更易于理解。
请尝试以下代码:
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 2) As String
lngRowCheck(1) = "B2:B18"
lngRowCheck(2) = "D2:D4"
Dim UnionRng As Range
Set UnionRng = Application.Union(Range("B2:B18"), Range("D2:D4"))
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For Each rngCell In UnionRng.Cells
If rngCell.Value = 0 Then
MsgBox ("Please enter a name in cell " & rngCell.Address)
rngCell.Select
Exit Sub
End If
Next
End Sub