【问题标题】:Excel Parent-Child Table to TreeExcel 父子表到树
【发布时间】:2015-06-06 18:55:32
【问题描述】:

所以我试图在excel中组织一个具有父子关系的进程列表。有超过 2000 个条目要组织,所以我想我会继续用宏来做。我搜索了一下,发现this question and answer 基本上详细说明了我想要什么。但是,当使用最佳答案中的代码时,我不断遇到此错误:

Run-time error '1004': Application-defined or object-defined error

根据 VBA 编辑器,代码在这一行失败:

Cells(Range("Destination").row + row, Range("Destination").Column + depth) = header

我知道这是一种转发,但我没有在其他地方找到帮助。

编辑:下面发布的完整代码。和原帖一样。

Sub MakeTree()

    Dim r As Integer
    ' Iterate through the range, looking for the Root
    For r = 1 To Range("Data").Rows.Count
        If Range("Data").Cells(r, 1) = "Root" Then
            DrawNode Range("Data").Cells(r, 2), 0, 0
        End If
    Next

End Sub

Sub DrawNode(ByRef header As String, ByRef row As Integer, ByRef depth As Integer)

'The DrawNode routine draws the current node, and all child nodes.
' First we draw the header text:
    Cells(Range("Destination").row + row, Range("Destination").Column + depth) = header

    Dim r As Integer
    'Then loop through, looking for instances of that text
    For r = 1 To Range("Data").Rows.Count
        If Range("Data").Cells(r, 1) = header Then
        'Bang!  We've found one!  Then call itself to see if there are any child nodes
            row = row + 1
            DrawNode Range("Data").Cells(r, 2), row, depth + 1
        End If
    Next

End Sub

【问题讨论】:

  • 您有一个名为Destination 的命名范围吗?否则,该行将失败。此外,如果您添加 your 代码而不是以前代码的链接,您的问题会更好。
  • 或者它也可以是header 变量。当它出错时,您可以进入调试模式,如果您将鼠标悬停在每个变量上,它会告诉您 VBA 与每个变量相关联的值。
  • Destination 是我定义的范围。抱歉表单不好,堆栈溢出的新手。

标签: vba excel


【解决方案1】:

Run-time error '1004' 在(除其他外)您尝试写入受保护工作表上的锁定单元格时发生。取消保护工作表或解锁您需要写入的单元格。

如果您想使用 VBA 保护/取消保护工作表,请查看 Worksheet 对象的 ProtectUnprotect 方法的帮助。完全限定您的范围所属的工作簿和工作表并使用 With ... End With 块也是一个好主意,例如

With Workbooks("book_name.xlsm").Worksheets("sheet_name")
    .Unprotect
    .Cells(.Range("Destination").row + row, .Range("Destination").Column + depth) = header
    .Protect
End With

Protect 方法有一堆您可能需要查看的可选参数(例如密码、允许过滤)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2018-05-23
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    相关资源
    最近更新 更多