在VBA中根据相关的下拉框清除单元格

我在I8有一个下拉框,我有一个依赖下拉框在I18指向I8。 如果在I8中select苹果1,当点击该框时,我将在I18中列出1-10水果。 说我在I18的盒子里select了Fruit 9。 那么问题是,我决定改变我的答案,苹果2,水果1-5将出现在I18,但6-10不会。 现在在I18,水果9仍然被选中,我将不得不点击来改变它。

如果我在selectapple1的时候select了水果6-10,并且我决定将其更改为apple2,我的i18将会变成空白。

这是我的代码:

Private Sub Worksheet_Change(ByVal Target As Range) On Error Resume Next If Target.Address = "$I$8" Then If Target.Address = "6" Or "7" Or "8" Or "9" Or "10" Then If Target.Validation.Type = 3 Then Application.EnableEvents = False Target.Offset(10, 0).ClearContents End If End If End If exitHandler: Application.EnableEvents = True Exit Sub End Sub 

几个问题。 请参阅重构代码中的注释。

 Private Sub Worksheet_Change(ByVal Target As Range) 'On Error Resume Next ->> delete this, it will not allow you to see real errors in your code If Target.Address = "$I$8" Then 'you ask it define Target.Address = 6, etc. Wrong property. You need Target.Value ( 'think about it, you just checked for Address = $I$8, so how can it also be 6 - 10 'also if you do want to use IF, syntax is Target.Value = 6 or Target.Value = 7 ... not 6 or 7 or ... Select Case Target.value 'used this as it more efficient Case 6 to 10 If Target.Validation.Type = 3 Then Application.EnableEvents = False Target.Offset(10, 0).ClearContents End If End Select End If exitHandler: Application.EnableEvents = True Exit Sub End Sub