答案 0 :(得分:1)
将此代码放在工作表代码窗格中:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Value <> "" Then '<--| bother only when user inputs values, not when he/she deletes them
If Cells(2, Target.Column) <> Cells(Target.Row, 1) Then '<--| if edited cell row (row 2) and column (column 1) headers don't match then ...
MsgBox "Sorry you must input a cell whose row and column headers match !" '<--|... inform the user...
Application.EnableEvents = False ' <--|... disable events not to have this event handler be called in an infinite loop,,,
Target.ClearContents '<--| clear the invalid userinput
Application.EnableEvents = True '<--| enable back events and have them run for subsequent user inputs
End If
End If
End Sub
答案 1 :(得分:0)
替代方法,通过锁定用户无法输入数据的所有单元格来阻止条目。
Sub StopEntries()
Dim ws As Worksheet
Dim wb As Workbook
Dim SheetRow As Integer
Dim SheetColumn As Integer
Const ColumnHeaderRow As Integer = 2
Const RowHeaderColumn As Integer = 1
Const NumberOfRows As Integer = 21
Const NumberOfColumns As Integer = 21
Set wb = Workbooks("TestBook.xlsx")
Set ws = wb.Worksheets("LockedSheet")
With ws
' lock all cells
ws.Cells.Locked = True
' unlock cells that meet the condition
For SheetRow = 1 To NumberOfRows
For SheetColumn = 1 To NumberOfColumns
If .Cells(SheetRow + ColumnHeaderRow, RowHeaderColumn) = .Cells(ColumnHeaderRow, SheetColumn + RowHeaderColumn) Then .Cells(SheetRow + ColumnHeaderRow, SheetColumn + RowHeaderColumn).Locked = False
Next SheetColumn
Next SheetRow
' protect the sheet
.Protect UserInterfaceOnly:=True
End With
End Sub