在 excel TreeView VBA 中编辑节点
Posted
技术标签:
【中文标题】在 excel TreeView VBA 中编辑节点【英文标题】:Edit a Node in excel TreeView VBA 【发布时间】:2016-12-29 08:45:38 【问题描述】:我正在为 excel 中的用户窗体编写树视图。我想让表单的用户能够编辑任何节点的名称并了解所需的 labelit 属性,但是我不确定编写代码的方式。感谢任何形式的帮助。
【问题讨论】:
【参考方案1】:您需要 Microsoft 的 ActiveX 控件,该控件可以追溯到 Visual Basic 6.0 时代(VBA 是 VB6 的变体)
试试这个
https://msdn.microsoft.com/en-us/library/ms172635(v=vs.90).aspx
通过转到控件工具箱,然后从列表Microsoft TreeView Control, version 6.0
中选择其他控件,将控件放置在表单上
使用对象浏览器并选择TreeView
类可以调查您需要使用的方法和事件。必须将LabelEdit
属性设置为tvwAutomatic
并允许系统处理编辑,然后使用AfterLabelEdit
捕获事件,或者将LabelEdit
属性设置为tvwManual
,如果用户双击节点然后你捕获这是DoubleClick
事件并手动调用StartLabelEdit
,使用AfterLabelEdit
来验证编辑。
一些链接:
LabelEdit Property
VB Coding Tip Treeview - Label-Editing
一些示例代码
Option Explicit
Private Sub TreeView1_DblClick()
Dim nodSelected As MSComctlLib.Node
Set nodSelected = TreeView1.SelectedItem
If nodSelected.Text <> "root" Then
TreeView1.StartLabelEdit
End If
End Sub
Private Sub UserForm_Initialize()
TreeView1.Style = tvwTreelinesPlusMinusText
TreeView1.LabelEdit = tvwManual
'Add some nodes to the TreeView
Dim nodRoot As MSComctlLib.Node
Set nodRoot = TreeView1.Nodes.Add(Key:="root", Text:="root")
'
Dim nodChildren(1 To 2) As MSComctlLib.Node
Set nodChildren(1) = TreeView1.Nodes.Add(nodRoot, tvwChild, "child 1", "child 1")
Set nodChildren(2) = TreeView1.Nodes.Add(nodRoot, tvwChild, "child 2", "child 2")
Dim nodGrandChildren(1 To 3) As MSComctlLib.Node
Set nodGrandChildren(1) = TreeView1.Nodes.Add(nodChildren(1), tvwChild, "grandchild 1", "grandchild 1")
Set nodGrandChildren(2) = TreeView1.Nodes.Add(nodChildren(2), tvwChild, "grandchild 2", "grandchild 2")
Set nodGrandChildren(3) = TreeView1.Nodes.Add(nodChildren(2), tvwChild, "grandchild 3", "grandchild 3")
End Sub
Private Sub TreeView1_AfterLabelEdit(Cancel As Integer, NewString As String)
' Make sure that we have a value in the Label
If Len(NewString) < 1 Then
' The Label is empty
MsgBox "Error! You must enter a value"
Cancel = True
Else
MsgBox "You successfully edited label to " & NewString
End If
End Sub
注意:点击根节点展开子节点(不明显)。
【讨论】:
您是否按照第 4 段所述将 TreeView 控件添加到用户窗体? 转到您的用户表单。然后从顶部菜单转到查看->工具箱。然后在新窗口的灰色空白区域右键单击并从弹出菜单中选择附加控件,然后在列表中找到并单击“Microsoft TreeView 控件,版本 6.0”并单击确定。然后会出现一个新的树形视图图标,单击并按住然后将其拖到您的表单中。控件的默认名称为 Treeview1。 如果您已经有 Treeview,那么我猜您调整了代码。我对文本编译错误感到困惑。在您的工具->参考中,您是否检查了Microsoft Windows Common Controls 6.0 (SP6)
?
让我们continue this discussion in chat。以上是关于在 excel TreeView VBA 中编辑节点的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Excel 2016 VBA 编辑器中启用 Unicode