Excel父子表到树

时间:2015-06-05 19:05:08

标签: excel vba excel-vba

所以我试图在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

1 个答案:

答案 0 :(得分:0)

当您尝试写入受保护的工作表上的锁定单元格时(其中包括),会发生

Run-time error '1004'。取消保护工作表或解锁您需要写入的单元格。

如果要使用VBA保护/取消保护工作表,请查看Protect对象的UnprotectWorksheet方法的帮助。也是一个好主意,可以完全限定您的范围所属的工作簿和工作表,并使用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方法有一堆可选参数(例如密码,允许过滤),您可能需要查看这些参数。

相关问题