繁体   English   中英

VBA以递归方式打开excel工作簿

[英]VBA opening excel workbooks in recursion

我正在尝试编写用于创建 excel workooks 网络地图的代码(例如一个文件包含指向其他七个文件的链接,而这些文件又具有指向可能不同文件的链接等)。 由于我不知道网络中所有文件的集合,我想通过递归来做到这一点。 我写了这段代码:

Sub recLink(strPath As String)
Dim WB As Workbook
Set WB = Workbooks.Open(strPath , False, True)

If Not IsEmpty(WB.LinkSources(xlExcelLinks)) Then
    For Each LNK In WB.LinkSources(xlExcelLinks)
        Debug.Print LNK
        Call recLink(Str(LNK))
    Next LNK
Else
End If

WB.Close (False)
End Sub

问题是在第二次迭代中尝试打开工作簿时,excel 应用程序关闭。 即使对于为测试目的而创建的小而简单的文件也是如此。

你能帮我完成这项工作吗? 我在这里缺少什么?

原因

The issue is on the Str(LNK) from "Call recLink(Str(LNK))".

解决方案

创建一个字符串变量并将LNK设置为该变量,然后您就可以使用字符串变量调用该函数。 这将起作用。

Dim strLink as String
.
.
strLink = LNK
Call recLink( strLink )
.
.

我是如何发现的

我才发现是因为我试图首先将所有链接放入数组中,而当 VBA 只是要使用 LNK 定义数组时,也会出现同样的问题。 所以我发现问题不可能是递归调用,唯一不同的是 STR() 函数。 arrLink(x) = Str(LNK)

我的建议

此代码使 Excel 的所有窗口都隐藏起来,演示文稿更漂亮,执行速度更快。

Function recLink(strPath As String)
   Dim objMaster              As Object
   Dim wbkMaster              As Workbook
   Dim strLink                As String

   Set objMaster = CreateObject("Excel.Application")
   With objMaster
      .Visible = False
      Set wbkMaster = .Workbooks.Open(strPath)

      If Not IsEmpty(wbkMaster.LinkSources(xlExcelLinks)) Then
          For Each LNK In wbkMaster.LinkSources(xlExcelLinks)
            strLink = LNK
            Debug.Print strLink
            Call recLink(strLink)
          Next LNK
      Else
      End If

   End With

   wbkMaster.Close (False)
   Set objMaster = Nothing
   Set wbkMaster = Nothing

End Function

结论

测试两个代码并选择最适合您的代码。

问候 周末愉快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM