以下是我用treeview控件按部门和员工显示设备领用情况代码.
Option Compare Database
Dim rec As New ADODB.Recordset
Dim recPlant As New ADODB.Recordset
Dim nodindex As Node
Dim keyDepa, strDepa
Dim keyEm, strEm
Dim keyPl, strPl
Private Sub Form_Load()
AutoMxID
'设置第一级"部门"
rec.Open "qry部门_升序", CurrentProject.Connection, adOpenKeyset, adLockOptimistic, adCmdTableDirect
For I = 0 To rec.RecordCount - 1
Set nodindex = Treeview.Nodes.Add(, , "部门" & rec.Fields("depaID"), rec.Fields("depa"), "k1", "k2")
rec.MoveNext
Next
rec.Close
nodindex.Sorted = False
'设置第二级"员工"
'* ---------------------------
rec.Open "qry员工_升序", CurrentProject.Connection, adOpenKeyset, adLockOptimistic, adCmdTableDirect
For I = 0 To rec.RecordCount - 1
Set nodindex = Treeview.Nodes.Add("部门" & rec.Fields("depaID"), tvwChild, "员工" & rec.Fields("emID"), rec.Fields("emName"), "k1", "k2")
recPlant.Open "Select tblplant.plantid, tblplant.plant, tblplant.emid" & " FROM qry员工使用的设备" & " Where tblplant.emid = '" & rec.Fields("emID") & "'", CurrentProject.Connection, adOpenKeyset, adLockOptimistic, adCmdTableDirect
For N = 0 To recPlant.RecordCount - 1
Set nodindex = Treeview.Nodes.Add("员工" & recPlant.Fields("emID"), tvwChild, "设备" & recPlant.Fields("PlantID"), recPlant.Fields("Plant"), "k1", "k2")
nodindex.Sorted = True
recPlant.MoveNext
Next N
recPlant.Close
nodindex.Sorted = True
rec.MoveNext
Next I
rec.Close
End Sub
Private Sub Treeview_NodeClick(ByVal Node As Object)
Dim nodindex As Node
点击事件为NodeClick
If Node.Key Like "部门*" Then
keyDepa = Mid(Node.Key, 3)
strDepa = Node.Text: Me.申报部门 = strDepa
End If
If Node.Key Like "员工*" Then
keyEm = Mid(Node.Key, 3)
strEm = Node.Text: Me.申报员工 = strEm
End If
If Node.Key Like "设备*" Then
keyPl = Mid(Node.Key, 3)
strPl = Node.Text: Me.设备名称 = strPl: Me.设备编号 = keyPl
End If
End Sub
方法二:treeview树节点及子窗体联动
Private Sub form_load()
Dim I As Integer
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT * FROM menu;") '以要链接的表建立记录集
If rst.RecordCount = 0 Then MsgBox "表中无数据!程序终止。": Exit Sub '如果链接表无数据
I = 1
rst.MoveFirst '记录首
While Not rst.EOF '循环记录
With Me.TreeView0.Nodes '每循环1条记录添加一个分类
.Add , 4, "s" & I, "" & rst(1) & ""
End With
I = I + 1
Me.win.SourceObject = "窗体1"
rst.MoveNext '下一条记录
Wend
End Sub
Private Sub TreeView0_Click()
If TreeView0.SelectedItem.Children = 0 Then '检查是否有子节点,0为无
For T = 1 To TreeView0.Nodes.Count
If TreeView0.Nodes(T).Selected Then
'MsgBox "您选择的是:" & TreeView0.Nodes(T).FullPath & "子节点!" '系统提示
Me.win.SourceObject = "窗体1"
End If
Next T
End If
End Sub