除了我的评论
例 1
创建一个名为 的工作表List
,它将存储您的值。这种方法最好的部分是您不必每次想要从列表中添加/删除项目时都修改代码。
见截图
假设这是你的主要工作表
将此代码粘贴到工作表代码区域
Dim rngList As Range, aCell As Range
Dim RowAr() As Long
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
On Error GoTo Whoa
Application.EnableEvents = False
For Each aCell In Target
If aCell.Row = 5 Then
With Application
For i = LBound(RowAr) To UBound(RowAr)
If RowAr(i) = aCell.Column Then
MsgBox "Change is not possible."
.Undo
GoTo Letscontinue
End If
Next
End With
End If
Next
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim wsList As Worksheet
Dim n As Long, lrow As Long
Set wsList = ThisWorkbook.Sheets("list")
With wsList
lrow = .Range("A" & .Rows.Count).End(xlUp).Row
Set rngList = .Range("A1:A" & lrow)
End With
n = 0
ReDim RowAr(n)
For Each aCell In Range("5:5")
If Len(Trim(aCell.Value)) <> 0 Then
If Application.WorksheetFunction.CountIf(rngList, aCell.Value) > 0 Then
n = n + 1
ReDim Preserve RowAr(n)
RowAr(n) = aCell.Column
Debug.Print aCell.Column
End If
End If
Next
End Sub
代码在行动
例 2
这使用硬编码列表。
Option Explicit
Dim RowAr() As Long, aCell As Range
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim MyList As String, MyAr() As String
Dim n As Long, i As Long
'~~> This is the list
MyList = "Header 1,Header 2"
MyAr = Split(MyList, ",")
n = 0
ReDim RowAr(n)
For Each aCell In Range("5:5")
If Len(Trim(aCell.Value)) <> 0 Then
For i = LBound(MyAr) To UBound(MyAr)
If aCell.Value = MyAr(i) Then
n = n + 1
ReDim Preserve RowAr(n)
RowAr(n) = aCell.Column
End If
Next
End If
Next
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
On Error GoTo Whoa
Application.EnableEvents = False
For Each aCell In Target
If aCell.Row = 5 Then
With Application
For i = LBound(RowAr) To UBound(RowAr)
If RowAr(i) = aCell.Column Then
MsgBox "Change is not possible."
.Undo
GoTo Letscontinue
End If
Next
End With
End If
Next
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub