1. 程式人生 > >VBA--用類實現組合框聯動

VBA--用類實現組合框聯動

1.首先,我們要建立一個類,即新增類模板,記得更改名字,並且在裡面新增相應的欄位,並且對其欄位和物件進行屬性約束,其具體程式碼如下:

Option Explicit
Private sprovince As String
Private scity As Object
'屬性:省
Property Let province(pro As String)
    sprovince = pro
End Property
Property Get province() As String
    province = sprovince
End Property
'屬性:市
Property Set city(ci As Object)
    Set scity = ci
End Property
Property Get city() As Object
    Set city = scity
End Property

Private Sub Class_Initialize()
     Set city = CreateObject("scripting.dictionary") '市為一個字典,儲存資料
    
End Sub

Private Sub Class_Terminate()
    Set city = Nothing '釋放空間
   
End Sub

2.在Excel表內匯入資料,具體資料如下圖所示

3.建立一個窗體,佈局和樣式如下圖所示

4.編寫窗體的觸發時間,及執行事件

Option Explicit
Dim arrdata() As clsdata '建立一個物件(clsdata)
Dim d As Object '定義一個字典


Private Sub probox_Change()
With citbox
    .Clear '清理文字
    .List = arrdata(d(probox.Text)).city.Keys '根據對應的省份獲取市的資訊
    .ListIndex = 0 '使複合框中預設顯示第一個資料
End With
End Sub


Private Sub UserForm_Initialize()
    Dim i As Integer, dic As Object
    Set dic = CreateObject("scripting.dictionary") '建立一個字典來儲存省的資料
    For i = 2 To 309
        dic(Cells(i, 1).Value) = ""  '將省份資訊存入dic
    Next i
    ReDim arrdata(dic.Count - 1) As clsdata '確定陣列的長度(有多少個省,長度就為多少)
    Set d = CreateObject("scripting.dictionary") 'city 字典
    For i = 0 To dic.Count - 1
        Set arrdata(i) = New clsdata '每增加一個省份,自動新增一個字典
        arrdata(i).province = dic.Keys()(i) '陣列的省份資訊等於dic字典的值
        d(arrdata(i).province) = i '每個省份對應一個編號
    Next i
    For i = 2 To 309
        arrdata(d(Cells(i, 1).Value)).city(Cells(i, 2).Value) = "" '根據省份來獲取對應的市
       
    Next i
    probox.List = dic.Keys '所有的省份
   
End Sub