Vba 允许多个条目的数据验证
为了允许用户在数据验证范围内插入多个条目,我写下了下面几行。因此,如果下拉列表包含以下元素:Vba 允许多个条目的数据验证,vba,excel,Vba,Excel,为了允许用户在数据验证范围内插入多个条目,我写下了下面几行。因此,如果下拉列表包含以下元素:x1、x2、x3、…、xn,则对于该范围内的任何单元格,可以先选择并插入x1值,然后在同一单元格中选择并插入x3,结果为:x1、x3,依此类推。 问题是,当用户希望删除其中一个值时,他会收到一个excel错误,提示用户已限制此单元格的值。因此,他必须删除单元格的全部内容,然后再次选择他想要的值。在这方面你能帮我改进一下吗 代码如下: Private Sub Worksheet_Change(ByVal T
x1、x2、x3、…、xn
,则对于该范围内的任何单元格,可以先选择并插入x1
值,然后在同一单元格中选择并插入x3
,结果为:x1、x3
,依此类推。
问题是,当用户希望删除其中一个值时,他会收到一个excel错误,提示用户已限制此单元格的值。因此,他必须删除单元格的全部内容,然后再次选择他想要的值。在这方面你能帮我改进一下吗
代码如下:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
If Target.count > 1 Then GoTo exitHandler
On Error Resume Next
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Intersect(Target, rngDV) Is Nothing Then
'Column 7 is the one to which is the code is applied
ElseIf Target.Column = 7 Then
Application.EnableEvents = False
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If oldVal = "" Then
Else
If newVal = "" Then
Else
Target.Value = oldVal _
& ", " & newVal
End If
End If
End If
exitHandler:
Application.EnableEvents = True
End Sub
通过VBA违反验证是可能的,这就是为什么您的代码首先可以工作的原因。删除条目是一种手动操作,其中单元格内容(逗号分隔的列表)将与验证列表进行比较。 您可以执行以下操作之一:
- 将单元格与验证一起仅用于项目选择,并将逗号分隔的选择写入其他单元格
- 为单元格编写编辑函数-这样,编辑结果将通过VBA再次写入单元格
- 将列表(以及所有可能的删除结果)添加到验证列表中(尽管非常混乱)
- 将单元格与验证一起仅用于项目选择,并将逗号分隔的选择写入其他单元格
- 为单元格编写编辑函数-这样,编辑结果将通过VBA再次写入单元格
- 将列表(以及所有可能的删除结果)添加到验证列表中(尽管非常混乱)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
If Target.Count > 1 Then GoTo exitHandler
On Error Resume Next
Set rngDV = Range("G:G")
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Intersect(Target, rngDV) Is Nothing Then
ElseIf Target.Column = 7 Then
Application.EnableEvents = False
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If oldVal = "" Then
Else
If newVal = "" Then
Else
Target.Value = oldVal & ", " & newVal
End If
End If
End If
exitHandler:
Application.EnableEvents = True
End Sub
试试下面的
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
If Target.Count > 1 Then GoTo exitHandler
On Error Resume Next
Set rngDV = Range("G:G")
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Intersect(Target, rngDV) Is Nothing Then
ElseIf Target.Column = 7 Then
Application.EnableEvents = False
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If oldVal = "" Then
Else
If newVal = "" Then
Else
Target.Value = oldVal & ", " & newVal
End If
End If
End If
exitHandler:
Application.EnableEvents = True
End Sub
那么,如果我们从范围G中删除一部分,它应该应用于同一单元格?那么如果我们从范围G中删除一部分,它应该应用于同一单元格?