文章背景:在使用VBA的用户窗体(userform)时,有时会用到二级下拉菜单
。比如选择院系(一级下拉菜单)后,班级(二级下拉菜单)的内容自动更新;选择省份后,该省份下面所属的市相应更新。接下来以省市为例,进行二级下拉菜单的功能实现。
表1的数据如下:
用户窗体的内容如下:
省份combox的名称
取为provinceselect
;城市combox的名称
取为cityceselect
。
用户窗体内的VBA代码如下:
代码语言:javascript复制Option Explicit
Private Sub provinceselect_Change()
'Populate city data
Dim i As Integer, j As Integer, nrow As Integer
Sheets("Sheet1").Select
'Clear old data, if exists
UserForm1.cityselect.Clear
nrow = Range("A65535").End(xlUp).Row
For i = 1 To nrow
j = 1
If Range("A1:A" & nrow).Cells(i, 1) = UserForm1.provinceselect.Text Then
Range("A" & i).Select
Do While Not IsEmpty(ActiveCell.Offset(j, 0))
UserForm1.cityselect.AddItem ActiveCell.Offset(j, 0)
j = j 1
Loop
UserForm1.cityselect.Text = ActiveCell.Offset(1, 0)
Exit For
End If
Next i
End Sub
Private Sub UserForm_Initialize()
'Populate Provinces
Dim ncategories As Integer, i As Integer
Sheets("Sheet1").Select
ncategories = WorksheetFunction.CountA(Columns("C:C"))
For i = 1 To ncategories
UserForm1.provinceselect.AddItem Range("C1:C" & ncategories).Cells(i, 1)
Next i
UserForm1.provinceselect.Text = Range("C1").Value
End Sub
窗体初始化时,将省份的数据填入;当省份的选项发生变化时,城市的信息也做相应的修改。
代码运行过程如下:
http://mpvideo.qpic.cn/0bf2pmcokaaejuadhv3sv5pvi66d4v5qjzia.f10002.mp4?
参考资料:
[1] Coursera课程(Excel/VBA for Creative Problem Solving, Part 3)