excelvbaexcel-4.0

Activating closed workbooks


I am using the function below to extract data from other workbooks.

Function GetValue(path, file, sheet, ref)

    'Retrieves a value from a closed workbook
    Dim myArg 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
    myArg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
    
    'Execute an XLM macro
    GetValue = ExecuteExcel4Macro(myArg)

End Function

I am calling this function like this:

Sub TestGetValue()
    Dim p As String, f As String
    Dim s As String, a As String
    p = "C:\Users\schaudha\Desktop\FIT transition\test simulation results"
    f = "all cancer rate.xml"
    s = "CONTENTS"
    a = "A1"
    MsgBox GetValue(p, f, s, a)
End Sub

This function seems to work only when the workbook is active. I mean, if I open the Excel file that I need data from and then run my subroutine, it works, but if it is closed, it doesn't work. I would also like it work when the workbook is closed. I am guessing I need to activate the workbook somehow before I use ExecuteExcel4Macro(myArg). How do I do that? I plan on using this function to extract data from thousands to cells from about a hundred workbooks, so I want to make this code as efficient as possible.


Solution

  • This works

    Function GetValue(path, file, sheet, ref)
    
    'Retrieves a value from a closed workbook
    Dim myArg As String
    
    Dim CurrBook As Workbook
    
    '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
    
    Application.Workbooks.Open (path & file)
    
    'Create the argument
    myArg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
    
    'Execute an XLM macro
    GetValue = ExecuteExcel4Macro(myArg)
    
    Application.Workbooks(file).Close (False)
    
    End Function