我的excel表格中有5个不同的列,每个列都有不同的数据验证规则。当用户通过键盘手动输入时,我的规则起作用。
但是,当复制粘贴数据从不同的来源,如notepad,one note等,我的验证不起作用。只有当您单独单击cell时,它才会起作用。
示例:我的列是like、Name, Employee ID, Plan ID, Client Name, Email ID等
我需要某种类型的VBA或公式,当用户从不同来源复制/粘贴数据时,我的数据验证自动工作。
发布于 2017-10-17 15:17:33
是的,我也遇到过同样的问题。我已经通过阻塞粘贴解决了这个问题。在模块中,我有一个代码:
Sub NotAllowPaste()
Dim UndoList As String
If ThisWorkbook.Name <> ActiveWorkbook.Name Then Exit Sub
With Application
.EnableEvents = False
UndoList = .CommandBars("Standard").Controls("&Undo").List(1)
If InStr(UndoList, "Paste") > 0 Or _
UndoList = "Keep Source Formatting" Or _
UndoList = "Drag and Drop" Then
.Undo
MsgBox "Pasting and ""drag and drop"" is forbidden in this workbook.", vbCritical
End If
.EnableEvents = True
End With
End Sub然后,在我已经放入的工作表代码中:
Private Sub Worksheet_Activate()
Application.DisplayFormulaBar = False
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
NotAllowPaste
End Sub
Private Sub Worksheet_Deactivate()
Application.DisplayFormulaBar = True
End Sub如你所见,我还禁用了公式栏,以防止用户直接复制到其中。这对我很管用。
发布于 2017-10-19 16:50:17
在normal模块中,子例程检查列表:
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验证-这可能会被用户在粘贴时无意中覆盖。我已经制作了一些宏,用黄色填充无效的单元格,但你可以命令它做其他的事情。如果你认为有人可能试图粘贴1000或更多的值,我不推荐msgbox。
https://stackoverflow.com/questions/46783636
复制相似问题