Excel Hacks

Page 365

HACK

#136

Retrieve Data from Closed Workbooks 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 'that contain the data in each worksheet and workbook. Const Con_stSQL As String = "SELECT * FROM [ProductData]"

'The ADO Recordset variable. Dim rst As ADODB.Recordset 'The connection string variable. Dim stCon As String 'String variable that holds the located Excel files. Dim stFile As String 'Variable to temporarily store the present calculation mode. Dim xlCalc As Excel.XlCalculation 'Variable for this workbook. Dim wbBook As Workbook 'Variable for the target worksheet. Dim wsTarget As Worksheet 'Variable to get the last used row in the target worksheet Dim lnLastRow As Long 'General error handling. On Error GoTo Error_Handling 'Temporarily change some settings to increase the performance. With Application 'Store the calculation mode. xlCalc = .Calculation 'Temporarily set the calculation mode to Manual. .Calculation = xlCalculationManual 'In case any Events procedures exist. .EnableEvents = False 'To avoid that the screen is flickering during the process. .ScreenUpdating = False End With 'Instantiate Set wbBook = 'Instantiate Set wsTarget

the workbook variable. ThisWorkbook the worksheet variable. = wbBook.Worksheets(1)

'Instantiate the Recordset object. Set rst = New ADODB.Recordset 'Get the first Excel file. stFile = Dir(Con_stPath & "*.xls", 7) 'Iterate through the collection of Excel files, 'open a connection to each file and retrieve the wanted data,

342

|

Chapter 8, Cross-Application Hacks


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.