Retrieving Data From Closed Workbook

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Retrieving Data From Closed Workbook

Post by jstevens »

Is it possible to retrieve data from a closed workbook using "readonly"? I cannot get it to work.

The code below works just fine for me but wanted to add: readonly:=true

Code: Select all

Public Function GetValue(P, F, S, ref)
'Retrieves a value from a closed workbook
Dim arg As String

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

'Create the argument
arg = "'" & P & "[" & F & "]" & S & "'!" & _
    range(ref).range("A1").Address(, , xlR1C1)

'Execute an XLM macro
    GetValue = ExecuteExcel4Macro(arg)
End Function
Regards,
John
Regards,
John

User avatar
HansV
Administrator
Posts: 78485
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Retrieving Data From Closed Workbook

Post by HansV »

You're not opening the workbook, so read-only doesn't come into it.
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: Retrieving Data From Closed Workbook

Post by jstevens »

Hans,

The source file that is read continually gets updated or I should say overwritten. If the code runs while the file is being overwritten then the process fails.

Any suggestions?

Regards,
John
Regards,
John

User avatar
HansV
Administrator
Posts: 78485
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Retrieving Data From Closed Workbook

Post by HansV »

Try this version of the function:

Code: Select all

Public Function GetValue(P, F, S, ref)
  'Retrieves a value from a closed workbook
  Dim arg As String
  Dim i As Integer

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

  'Create the argument
  arg = "'" & P & "[" & F & "]" & S & "'!" & _
    Range(ref).Range("A1").Address(, , xlR1C1)

  On Error Resume Next
  ' Up to 10 attempts
  For i = 1 To 10
    Err.Clear
    'Execute an XLM macro
    GetValue = ExecuteExcel4Macro(arg)
    ' Get out if we succeeded
    If Err = 0 Then Exit Function
    ' Wait for one second
    Application.Wait Now + TimeSerial(0, 0, 1)
  Next i

  'We only get here if all failed
  GetValue = "Error retrieving value"
End Function
It will attempt up to 10 times to retrieve the value, at 1 second intervals.
Best wishes,
Hans