Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use VBScript to effectively refresh the external data of several Excel spreadsheets?

I have a macro in one XLSM workbook's module that refreshes all the external data, then saves and closes that workbook.

ActiveWorkbook.RefreshAll
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.Quit

I use a VBScript file to run that macro as part of a scheduled task

objExcel.Workbooks.Open(fname)
objExcel.Visible = True
On error resume next
objExcel.Run "RefreshAllData"

Question: How can I reuse the existing macro in the existing workbook to refresh all the data of multiple other workbooks? (ie. I'm looking for the necessary modifications to the VBScript file, I want to minimise changes to the macro itself. The filenames will be contained in the VBScript file) TIA.

like image 244
Sam Avatar asked Jun 05 '13 05:06

Sam


People also ask

How do you refresh external data in Excel?

Click a cell in the external data range. On the Data tab, in the Connections group, click Refresh All, and then click Connection Properties. Click the Usage tab. Select the Refresh every check box, and then enter the number of minutes between each refresh operation.

How do I refresh an Excel spreadsheet using VBA?

You can trigger a data refresh when your Excel file is first opened by pasting VBA code into the Workbook_Open event. Simply double-click the ThisWorkbook object in the VBA Project Pane to open the text editor (blank white sheet) within the Visual Basic Editor (keyboard shortcut Alt +F11).


1 Answers

I'd recommend against re-using a trivial macro like that. Instead incorporate the refresh functionality in the VBScript:

Set fso = CreateObject("Scripting.FileSystemObject")
Set xl  = CreateObject("Excel.Application")
xl.Visible = True

For Each f In fso.GetFolder("C:\some\folder").Files
  If LCase(fso.GetExtensionName(f.Name)) = "xlsx" Then
    Set wb = xl.Workbooks.Open(f.Path)
    wb.RefreshAll
    wb.Save
    wb.Close
  End If
Next

xl.Quit
like image 119
Ansgar Wiechers Avatar answered Sep 25 '22 03:09

Ansgar Wiechers