在我的 Excel 工作表中,我驗證特定列不應為空且其值應是唯一的。此驗證只能在「Sheet1」上執行,但它也適用於其他工作表。我的程式碼是
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _ Cancel As Boolean)
Dim rngCell As Range
Dim lngLstRow As Long
lngLstRow = ActiveSheet.UsedRange.Rows.Count
For Each rngCell In Range("A1:A" & lngLstRow)
If rngCell.Value = 0 Then MsgBox ("Please enter a name in cell " & rngCell.Address) rngCell.Select
End If
Next
End Sub
唯一值的第二次驗證是透過 Excel 中的資料驗證功能完成的。
答案1
您應該指定您希望程式碼執行的工作表,而不是使用 ActiveSheet。
因此,如果您想檢查 Sheet1,您可以將其變更為:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim rngCell As Range
Dim lngLstRow As Long
lngLstRow = Sheet1.UsedRange.Rows.Count
For Each rngCell In Sheet1.Range("A1:A" & lngLstRow)
If rngCell.Value = 0 Then
MsgBox "Please enter a name in cell " & rngCell.Address
Sheet1.Activate
rngCell.Select
End If
Next
End Sub