获取封闭工作簿中定义名称的path,文件名,表单和地址

此代码可以将已定义的名称添加到另一个工作簿中:

Sub AddDefinedName() Dim sPath As String Dim sFilename As String Dim sSheetname As String Dim sRangeAddress As String sPath = "C:\Me\Folder" sFilename = "source.xls" sSheetname = "Sheet1" sRangeAddress = "$A$1:$B$5" ThisWorkbook.Names.Add "Source", _ RefersTo:="='" & sPath & "\[" & sFilename & "]" & sSheetname & "'!" & sRangeAddress End Sub 

如果所述工作簿已打开,则此代码可以获取所有信息:

 Sub GetDefinedName() Dim sPath As String Dim sFilename As String Dim sSheetname As String Dim sRangeAddress As String sPath = Range("Source").Parent.Parent.Path sFilename = Range("Source").Parent.Parent.Name sSheetname = Range("Source").Parent.Name sRangeAddress = Range("Source").Address MsgBox sPath MsgBox sFilename MsgBox sSheetname MsgBox sRangeAddress End Sub 

如何closures工作簿“source.xls”(因此可以通过VBA打开)。

您可以使用Name对象来获取地址string,就像这样
(假设您已将该名称定义为“ Workbook范围”)

 Dim nm as Name Set nm = ThisWorkbook.Names("Source") Debug.Print nm.RefersTo 

这将给你的forms完整的path和地址

 '=C:\Me\Folder\[source.xls]Sheet1'!$A$1:$B$5 

注意:如果path,文件名或工作表名称中没有空格,则不包含'

以上将返回特定命名范围的信息。 如果你想获得所有远程引用的信息,请尝试使用

 ThisWorkbook.LinkSources 

这将以stringforms返回所有链接源的数组。 对于其他工作表的链接,它将在表单中

 C:\Me\Folder\source.xls 

你可以打开它并再次closures它,我知道它不是“物理上打开它”,但它做同样的工作。 请注意,运行此代码时,将触发“源”工作簿的Workbook_OpenWorkbook_close中的任何macros:

 Sub GetDefinedName() Application.ScreenUpdate = False Dim sPath As String Dim sFilename As String Dim sSheetname As String Dim sRangeAddress As String sPath = Range("Source").Parent.Parent.Path sFilename = Range("Source").Parent.Parent.Name sSheetname = Range("Source").Parent.Name sRangeAddress = Range("Source").Address Application.Workbooks.Open sPath & sFilename MsgBox sPath MsgBox sFilename MsgBox sSheetname MsgBox sRangeAddress sFilename.close False Application.ScreenUpdate = True End Sub