MrExcel Publishing
Your One Stop for Excel Tips & Solutions

Referencing a closed workbook

Posted by Alex on December 30, 2001 11:44 PM


1) Why this function doesnt work when i call from the excel worksheet as a fuction ? i.e. entering
=MyGetValue2 to the cell will return an error (#VALUE)

2) Lets say i call this funtion from another macro embedded in open.xls. How can i get the cell from the closed workbook (closed.xls) to be copied to another cell address instead of exactly same cell address in the open workbook (open.xls). i.e. I wanna get the value at the cell A2 in closed.xls to say the cell A1 in open.xls ?

Public Function MyGetValue2()
' Retrieves a value from a closed workbook
Dim arg As String

path = "c:\My Documents"
file = "closed.xls"
sheet = "Sheet1"
ref = "A2"

' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
MyGetValue2 = "File Not Found"
Exit Function
End If

' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)

' Execute an XLM macro
MyGetValue2 = ExecuteExcel4Macro(arg)
End Function

Posted by Gary Bailey on December 31, 2001 8:40 AM

AFAIK you cannot use ExecuteExcel4Macro in a UDF. Its part of the "you can't do anything that changes the structure of the workbook in a UDF" restriction - even if this particular Excel 4 Macro won't change the structure.

The idea of calling the Excel4Macro to reference a closed workbook with a variable name should work if you call the function from a macro though.



Posted by Alex on December 31, 2001 11:27 AM


Thanks, at least u saved me lotta time figuring out why it doesnt work.... what does AFAIK mean ?

Posted by Gary Bailey on December 31, 2001 11:56 AM

AFAIK = As far as I know. Nothing technical or exciting.