I'm trying to write code for creating the map of excel workooks network (like one file with links to seven other files, which in turn have their own links to maybe different files, etc.). Since I don't know a priori the set of all files in the network, I want to do this by recursion. I've written this piece of code:
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
and the problem is the excel app shuts down when trying to open a workbook in the second iteration. That is true even for small and simple files created for the purpose of testing.
Can you please help me with making this work? What am I missing here?
The cause
The issue is on the Str(LNK) from "Call recLink(Str(LNK))".
The solution
Create a string variable and set LNK to this var, then you can call the function using the string variable. This will work.
Dim strLink as String
.
.
strLink = LNK
Call recLink( strLink )
.
.
How I found
I only discovered because I was trying to put all links in array first, and the same issue occoured when VBA was simply going to define the array with LNK. So I figure out that the issue could not be the recursive call and the only thing that was different was the STR () function. arrLink(x) = Str(LNK)
My sugestion
This code keep all the windows of Excel hide, the presentation prettier and the execution faster.
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
Conclusion
Test both codes and choose what is the best for you.
Regards Have a nice weekend.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.