2017-03-29 27 views
1

我在I8中有一个下拉框,并且在I18中有一个依赖下拉框,正指向I8。如果在I8中选择苹果1,当我点击该框时,我将在I18中列出1-10水果。假设我在I18的盒子中选择了Fruit 9。那么,问题是,我决定改变我的苹果2的I8答案,水果1-5将出现在I18,但6-10不会。现在在I18中,水果9仍然被选中,我将不得不点击来改变它。根据VBA中的依赖下拉框清除单元格

如果我在选择apple1的时候选择了水果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 

回答

2

的几个问题。请参阅重构代码中的说明。

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 
+0

我做了您建议的更改@ScottHoltzman。但是,现在我的I18值总是被清除,不管Case值如何。建议? – Derrick

+0

*(+ 1)*我特别喜欢'Case ... sellect'的方法。通常,我会检查'如果Target.Value> = 6和Target.Value <= 10 Then'。但是这并没有考虑到Target.Value可能是一个字符串或Empty或一个错误值的可能性。使用'Case .... Select'你不关心,也不必确定'Target.Value'实际上是在我通常使用的'If'之前的'IsNumeric()'。这种方式更清洁,更简单,更直接。 – Ralph

+0

@Derrick - 你是否逐行通过代码来测试行为与期望值? –