I am trying to write a VBA function so that I can access the cell values of a closed Excel Workbook. I found online that one can write a macro routine like this:
Public Sub TestGetValue()
p = "C:\Users\Jake\Desktop"
f = "TestSample.xlsx"
s = "Sheet1"
a = "B10"
Call GetValue(p, f, s, a)
x = GetValue(p, f, s, a)
MsgBox x
End Sub
Public Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
range(ref).range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
I can run the TestGetValue()
as a macro, but when I try to use GetValue()
as a custom VBA function directly in Excel cells it doesn't work. It seems that the line GetValue = ExecuteExcel4Macro(arg)
cannot be executed.
Does anyone know how to get around that? I'm using Excel 2010.