HACK
#136
Retrieve Data from Closed Workbooks
The $ sign indicates that the worksheet exists. To select all data in one range, we could use either of two alternatives. Here’s how to use select data explicitly, using a range address: "SELECT * FROM [WorksheetName$A2:A10]"
And here’s how to use a named range (where the range name is unique for the workbook): "SELECT * FROM [NamedRange]"
If we want to retrieve a value from only one cell, then we still need to refer to a range, like so: "SELECT * FROM [WorksheetName$A2:A2)"
If we use a range name, it must cover a range, like A2:A2: "SELECT * FROM [NamedRange]"
In our example, all workbooks are identical and all of them are placed in the same folder: C:\Products. A worksheet with the name Summary exists in all workbooks, and the range name ProductData refers to the range A2:D6, as shown in Figure 8-2.
Figure 8-2. One of the identical workbooks, showing data
The code. In the workbook into which you want to import all of your data (let’s call it the final workbook), right-click, select View Code to take you to the VBE, select Insert ➝ Module, and paste the following code: Option Explicit 'A reference to Microsoft ActiveX Data Objects 'set via Tools ➝ References...
Library 6.0 must be
Sub Retrieve_Data_Closed_Workbooks( ) 'Constant variable that holds the directory. Const Con_stPath As String = "C:\Products\" 'The SQL statement string variable which only include the name for the range
338
|
Chapter 8, Cross-Application Hacks