Excel VBA 根據下拉框單元格的值來改變另外一個下拉框單元格的值

在不少的報表開發中,須要用到VBA去設置Excel的一些規則。 spa

如下是一個根據下拉框單元格的值來給特定單元格進行賦值的代碼:code

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error Resume Next:
    Application.ScreenUpdating = False
    If Target.Column = 7 Then        // 這是須要賦值的DDL列
        If Target.Offset(0, -2).Value = 13 Then  //表示賦值列往前移動兩個單位的格子值
            With Selection.Validation
            .Delete
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
             xlBetween, Formula1:="No"   //賦值爲No
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .IMEMode = xlIMEModeNoControl
            .ShowInput = True
            .ShowError = True
            End With
        ElseIf Target.Offset(0, -2).Value <> 13 Then
            With Selection.Validation
            .Delete
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
             xlBetween, Formula1:="=Exp"  //這裏的Exp爲自定義名字的列做爲數據來源(Formulas -〉Name managers ) 
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .IMEMode = xlIMEModeNoControl
           .ShowInput = True
            .ShowError = True
            End With
        End If
    ElseIf Target.Column = 8 Then   //下面的邏輯用來控制,當第7列值爲No時,會把第8,910,11列保護起來不能輸入
        If Target.Offset(0, -1).Value = "No" Then
            Target.Locked = True
            Target.Offset(1, -6).Select
        End If
    ElseIf Target.Column = 9 Then
        If Target.Offset(0, -2).Value = "No" Then
            Target.Locked = True
            Target.Offset(1, -7).Select
        End If
    ElseIf Target.Column = 10 Then
        If Target.Offset(0, -3).Value = "No" Then
            Target.Locked = True
            Target.Offset(1, -8).Select
        End If
    ElseIf Target.Column = 11 Then
        If Target.Offset(0, -4).Value = "No" Then
            Target.Locked = True
            Target.Offset(1, -9).Select
        End If
    End If
    Application.ScreenUpdating = True
     
End Sub
相關文章
相關標籤/搜索