问题
This code can add a defined name to another workbook perfectly fine:
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
And this code allows to get all the information IF the said workbook is open:
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
How can I get these when the workbook "source.xls" is closed (so I can open it through VBA).
回答1:
You can use the Name object to get the address string, like this
(assuming you have defined the name as Workbook scope)
Dim nm as Name
Set nm = ThisWorkbook.Names("Source")
Debug.Print nm.RefersTo
This will give you the full path and address in the form
'=C:\Me\Folder\[source.xls]Sheet1'!$A$1:$B$5
Note: without the ''s if there are no spaces in the path, filename or sheet name
The above will return info for a specific named range. if you want to get info for all remote references, try using
ThisWorkbook.LinkSources
This will return an array of all link sources as strings. For links to other worksheets, it will be in the form
C:\Me\Folder\source.xls
回答2:
You could just open it and close it again, I know it's not the same as "not opening it physically" but it does the same job. Just be aware that any macros that are in the "Source" workbook's Workbook_Open and Workbook_close will be fired when this code runs:
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
来源:https://stackoverflow.com/questions/24383054/get-path-filename-sheet-and-address-of-defined-name-in-closed-workbook