子程序檢查對列表中,正常的模塊中:
Sub ListToCheck(rng As Range)
Dim cl As Range
Dim i As Integer
Dim bMatch As Boolean
Dim sListName As String
sListName = "sheet2!MyList" 'change this accrording to your needs
bMatch = False
For Each cl In rng.Cells
With WorksheetFunction
For i = 1 To .CountA(Range("MyList"))
If cl.Value = .Index(Range(sListName), i) Then bMatch = True
Next i
End With
With cl.Interior
If bMatch Then
.ColorIndex = 0
Else
.Color = vbYellow
End If
End With
bMatch = False
Next cl
End Sub
,另一個用於檢查,如果兩個長材之間插入值:
Sub ValueToCheck(rng As Range, minV As Long, maxV As Long)
Dim cl As Range
Dim bOk As Boolean
For Each cl In rng.Cells
With cl
If IsNumeric(.Value) Then
If .Value < minV Or .Value > maxV Then
.Interior.Color = vbYellow
Else
.Interior.ColorIndex = 0
End If
Else
.Interior.Color = vbYellow
End If
End With
Next cl
End Sub
然後,一個在小宏使用驗證時應使用以下表格:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim col As Range
Dim colAdr As String
For Each col In Target.Columns
colAdr = col.Address(ReferenceStyle:=xlR1C1)
Select Case Right(colAdr, Len(colAdr) - InStrRev(colAdr, "C"))
Case Is = 1
ListToCheck col
Case Is = 2
ValueToCheck col, 1000000, 9999999
End Select
Next col
End Sub
我假定第一列是要檢查一下列表,第二個應該在1000000和9999999之間。但是你可以相應地修改它。正如你所看到的,我不使用excel驗證 - 這可能會在粘貼時被用戶無意中覆蓋。我已經用宏來填充非有效的單元格,但是您可以命令它執行其他操作。如果您認爲有人可能會嘗試粘貼1 000或更多的值,我不會推薦msgbox。
看到這裏的例子,如果規則將被覆蓋顯示一條消息https://stackoverflow.com/questions/29386971/force-pasted-values-to-obey-data-validation-rules – QHarr