Excel:检查工作簿中的工作表依赖关系?

Mar*_*tin 6 excel vba excel-2003 excel-vba

我正在重构一个巨大的工作簿,包括许多遗留部分,冗余计算,交叉依赖等.

基本上,我正在尝试删除不需要的工作表并在工作簿中实现一些适当的信息流.有没有一种很好的方法来提取工作表之间的依赖关系(使用VBA)?

谢谢马丁

Cha*_*ams 5

您可以使用ShowPrecedents和NavigateArrow。这是一些伪代码

for each oCell in oSht containing a formula
ocell.showprecedents
do until nomoreprecedents
i=i+1
Set oPrec = oCell.NavigateArrow(True, 1, i)
If not oPrec.Parent Is oSht Then
' off-sheet precedent
endif
loop
next ocell
Run Code Online (Sandbox Code Playgroud)


Mar*_*tin 0

我想出了一个小子来做到这一点。它将所有工作表移动到单独的工作簿中并打印出依赖关系。相对于使用的优点showPrecedents是它捕获所有链接,包括名称、嵌入的表单/图表等。

警告:移动工作表是不可撤消的,请在运行此操作之前保存工作簿,然后关闭(不保存)并重新打开。

Sub printDependencies()
    ' Changes workbook structure - save before running this
    Dim wbs As VBA.Collection, wb As Workbook, ws As Worksheets
    Dim i As Integer, s As String, wc As Integer
    Set ws = ThisWorkbook.Worksheets
    Set wbs = New VBA.Collection
    wbs.Add ThisWorkbook, ThisWorkbook.FullName

    For i = ws.Count To 2 Step -1
        ws(i).Move
        wc = Application.Workbooks.Count
        wbs.Add Application.Workbooks(wc), Application.Workbooks(wc).FullName
    Next
    Dim wb As Workbook

    For Each wb In wbs
        For Each s In wb.LinkSources(xlExcelLinks)
            Debug.Print wb.Worksheets(1).Name & "<-" & wbs(s).Worksheets(1).Name
        Next
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)

该代码不是很优美或用户友好,但它可以工作。