使用vba达到excel中下拉选项可多选的效果,查看网上的代码,成功做出来了,可是却会无限循环 5
求助怎么禁止无限循环代码如下SubWorksheet_Change(ByValTargetAsRange)'让数据有效性选择可以多选,重复选Application.Ena...
求助怎么禁止无限循环
代码如下
Sub Worksheet_Change(ByVal Target As Range)
'让数据有效性选择 可以多选,重复选
Application.EnableEvents = False
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
'do nothing
Else
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
比如比如原单元格式写着“张三”,我删除张,然后显示出来了“张,张三”,它会不停自动复制。 展开
代码如下
Sub Worksheet_Change(ByVal Target As Range)
'让数据有效性选择 可以多选,重复选
Application.EnableEvents = False
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
'do nothing
Else
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
比如比如原单元格式写着“张三”,我删除张,然后显示出来了“张,张三”,它会不停自动复制。 展开
展开全部
这段程序的原理简单说一下,你在下拉菜单里选一个值,这个值会保存下来为新值(newVal),然后undo,取到单元格修改前的值(oldVal),再把这两个值用逗号连起来。而你删除时也是在修改单元格,也会形成一个新值,这个新值并不是下拉菜单里选的。
比如原来单元格里是"1,2,3",下拉菜单里有1,2,3,你下拉菜单选1,那么新值就是1,和旧值合并为“1,2,3,1”如果你删除单元格里的3,那么新值为“1,2,”那么和旧值合并为"1,2,3,1,2,"
所以如果想删除东西,最好删除以后编辑状态下复制单元格内容,然后清空单元格再粘贴进去
比如原来单元格里是"1,2,3",下拉菜单里有1,2,3,你下拉菜单选1,那么新值就是1,和旧值合并为“1,2,3,1”如果你删除单元格里的3,那么新值为“1,2,”那么和旧值合并为"1,2,3,1,2,"
所以如果想删除东西,最好删除以后编辑状态下复制单元格内容,然后清空单元格再粘贴进去
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询