用EXCEL實現三級聯動的vba代碼

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
Dim tempStr As String

Dim firstDrawBoxRowCount As Integer
Dim firstDrawBoxColumn As Integer

firstDrawBoxRowCount = 15   --三級聯動第一級的單元格行數 ---隱藏的單元格
firstDrawBoxColumn = 1        ---三級聯動第一級的單元格列數---隱藏的單元格

Dim secondDrawBoxRowCount As Integer
Dim secondDrawBoxColumn As Integer

secondDrawBoxRowCount = 84 ----三級聯動第二級的單元格行數---隱藏的單元格
secondDrawBoxColumn = 4  ----三級聯動第二級的單元格列數 ---隱藏的單元格


If Target.Column = 13 Then ------------三級聯動第一級的單元格列數---選擇第一級顯示第二級
     Cells(Target.Row, Target.Column + 1) = ""
     Cells(Target.Row, Target.Column + 2) = ""
     For i = 2 To firstDrawBoxRowCount + 1
        If Trim(Cells(Target.Row, Target.Column)) = Trim(Cells(i, firstDrawBoxColumn)) Then
            tempStr = Trim(Cells(i, firstDrawBoxColumn + 1))
            Cells(Target.Row, Target.Column + 1).Select
                With Selection.Validation
                    .Delete
                    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                    xlBetween, Formula1:=tempStr
                    .IgnoreBlank = True
                    .InCellDropdown = True
                    .InputTitle = ""
                    .ErrorTitle = ""
                    .InputMessage = ""
                    .ErrorMessage = ""
                    .IMEMode = xlIMEModeNoControl
                    .ShowInput = True
                    .ShowError = True

                End With
            Exit For
        End If
     Next i
ElseIf Target.Column = 14 Then------三級聯動第二級的單元格列數---選擇第二級顯示第三級
    For i = 2 To secondDrawBoxRowCount + 1
        If Trim(Cells(Target.Row, Target.Column)) = Trim(Cells(i, secondDrawBoxColumn)) Then
            tempStr = Trim(Cells(i, secondDrawBoxColumn + 1))
             If tempStr = "" Then
               tempStr = " "
             End If
            Cells(Target.Row, Target.Column + 1).Select
                With Selection.Validation
                    .Delete
                    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                    xlBetween, Formula1:=tempStr
                    .IgnoreBlank = True
                    .InCellDropdown = True
                    .InputTitle = ""
                    .ErrorTitle = ""
                    .InputMessage = ""
                    .ErrorMessage = ""
                    .IMEMode = xlIMEModeNoControl
                    .ShowInput = True
                    .ShowError = True
                End With
            Exit For
        End If
     Next i
End If

End Sub

 

 

紅色部分是用宏錄製的vba

我做了個省市區三級聯動的簡單例子http://download.csdn.net/source/1495163 ,免分下載,呵呵,

有不明白的,可以留言問。

好了,肚子餓了去吃飯啦!!!

發佈了22 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章