2016-12-29 228 views
1

我正在为excel中的用户窗体编写树视图。我希望允许表单的用户能够编辑任何节点的名称并理解标记的属性是必需的,但我不确定编写代码的方式。任何形式的帮助表示感谢。在excel中编辑节点TreeView VBA

回答

1

你需要从微软追溯到时代的一个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 

注:点击根展开子节点(不是很明显)。

+0

如第4段所述,您是否将TreeView控件添加到用户窗体? –

+0

转到您的用户表单。然后从顶部菜单进入查看 - >工具箱。然后在灰色空白区域的新窗口中右键单击并从弹出菜单中选择附加控件,然后在列表中找到并单击“Microsoft TreeView控件6.0版”,然后单击确定。然后会出现一个新的树状图标,点击并按住,然后将其拖动到您的表单中。控件的默认名称将是Treeview1。 –

+0

如果你已经有了Treeview,那么我想你会修改代码。我对文本编译错误感到困惑。在你的工具 - >参考文件中,你是否检查过“Microsoft Windows Common Controls 6.0(SP6)”? –