VBA根据下拉选择更改单元格值

时间:2015-12-01 04:51:53

标签: excel vba excel-vba

我对VBA真的不太棒,终于停了下来。

我正在尝试根据我从下拉列表中选择的内容自动更改2个单元格值(在同一行中)。

Column L - Drop down consists of Won, Lost, Quote 

Column H - GO% 

Column I - GET% 

我想要实现的目标 -

If "Won" selected, then GO and GET cells equal 100%

If "Lost selected, then GO and GET cells equal 0%

我可以使用此公式来实现结果,但我还需要用户能够手动将数据输入GO和GET单元格,有效地擦除公式=IF($L5="Won",1,IF($L5="Lost",0,""))

我的数据从第5行开始,但我需要循环,因为我有500行相同。

如果有人可以提供帮助,请提前致谢:)

电子表格的屏幕截图

screenshot of spreadsheet

2 个答案:

答案 0 :(得分:1)

使用下面的代码,您可以选择下拉列表和列,并自动选择col H&我将被编译,否则如果家伙改变单元格H上的值或我下拉项目(在同一行中)更改为“引用”,立即看到所有更改。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim controlRng, nRng As Range
    Set controlRng = Range("L2:L500", "H2:I500")
    Set nRng = Intersect(controlRng, Target)
Application.EnableEvents = False
    If nRng Is Nothing Then Exit Sub

    Select Case Target.Column
    Case 12
        If Target.Value = "Won" Then
            Target.Offset(0, -4) = 1
            Target.Offset(0, -3) = 1

        ElseIf Target.Value = "Lost" Then
            Target.Offset(0, -4) = 0
            Target.Offset(0, -3) = 0
        Else
            'Do Something
        End If
    Case 8
        Target.Offset(0, 4) = "Quoted"
    Case 9
        Target.Offset(0, 3) = "Quoted"
    End Select
Application.EnableEvents = True
End Sub

答案 1 :(得分:0)

当单元格的值发生变化时,如果目标落入controlRng

,则会触发此代码

下面的代码无法在Module中添加,必须附上您应用的工作表下拉列表。 在我的例子中是Sheet1,如下所示:

enter image description here

Private Sub Worksheet_Change(ByVal Target As Range)

Dim controlRng, nRng As Range
    Set controlRng = Range("E2:E500")
    Set nRng = Intersect(controlRng, Target)

    If nRng Is Nothing Then Exit Sub

    If Target.Value = "Won" Then
        Target.Offset(0, -4) = 1
        Target.Offset(0, -3) = 1

    ElseIf Target.Value = "Lost" Then
        Target.Offset(0, -4) = 0
        Target.Offset(0, -3) = 0
    Else
        'Do Something
    End If

End Sub

enter image description here