TTom
Well-known Member
- Joined
- Jan 19, 2005
- Messages
- 518
I found the following code to get values from a closed workbook.
The problem is this is rather slow if the range of cells is large since it collects data cell by cell and not as a range.
Lets say I am getting values for Range(A1:E100), the function and proceedure go through 500 cells one at a time to get data, vs. one step to get entire range all at once.
Make sense?
***
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
Sub Import_From_Closed_Workbook
f = "FileToBeImportedFrom.xls"
p = "C:\ImportFromFolder"
s = "Sheet1" 'enables to specify which sheet
a = "A1:E100" 'range to be imported
NumberOfRows = Range(a).Rows.Count
NumberOfColumns = Range(a).Columns.Count
For r = 1 To NumberOfRows
For c = 1 To NumberOfColumns
b = Range(a).Cells(r, c).Address
Range("a2").Cells(r, c) = GetValue(p, f, s, b)
Next c
Next r
End Sub
The problem is this is rather slow if the range of cells is large since it collects data cell by cell and not as a range.
Lets say I am getting values for Range(A1:E100), the function and proceedure go through 500 cells one at a time to get data, vs. one step to get entire range all at once.
Make sense?
***
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
Sub Import_From_Closed_Workbook
f = "FileToBeImportedFrom.xls"
p = "C:\ImportFromFolder"
s = "Sheet1" 'enables to specify which sheet
a = "A1:E100" 'range to be imported
NumberOfRows = Range(a).Rows.Count
NumberOfColumns = Range(a).Columns.Count
For r = 1 To NumberOfRows
For c = 1 To NumberOfColumns
b = Range(a).Cells(r, c).Address
Range("a2").Cells(r, c) = GetValue(p, f, s, b)
Next c
Next r
End Sub