如何优化打开和closuresexcel工作簿来提取数据运行更快

我目前知道有两种方法可以打开和closuresexcel工作簿,从中提取数据并在一个工作簿中进行汇总。

第一种方法如下:

Dim wbDataSheet As Workbook For FNum = LBound(MyFiles) To UBound(MyFiles) Set wbDataSheet = Workbooks.Open(MyPath & MyFiles(FNum), 0, True) 'Capture data wbDataSheet.Close (False) Next FNum 

其次是这样的:

 Dim XL As New Excel.Application For FNum = LBound(MyFiles) To UBound(MyFiles) With XL .Workbooks.Open FileName:=MyPath & MyFiles(FNum), ReadOnly:=True .Visible = False End With 'Capture Data XL.ActiveWorkbook.Close False Next FNum 

我的困境是这样的:

方法1更快(大约.35秒/文件为1052个文件),但它爆炸我的任务栏,因为它打开新的工作簿(几乎不可能select一个不同的Excel工作簿),由于某种原因,我的代码可以很容易地通过按转移不止一次或者根本没有,迫使我开始编码。

方法2明显较慢(对于1052个文件大约为.56秒/文件),但是由于excel应用程序被隐藏,我的任务栏仍然可用,按shift不会中断代码。

我想知道的是,是否有方法来运行方法1,而不会损坏我的任务栏或有转移停止代码? 另外,有没有办法加快方法二到方法1附近的速度?

*注:我已经使用下面的代码来优化我的速度和限制VBA /工作簿交互。 除了访问工作簿的方法之外,每种情况下的其余代码都是相同的。

 With Application .Calculation = xlCalculationManual .ScreenUpdating = False .EnableEvents = False .DisplayAlerts = False End With 

调用使用ExecuteExcel14Macro的Get值函数的示例代码

 Sub test() Dim p As String, f As String, s as String, a as String p = "C:\Users\User\Documents\" f = "Example.xlsx" s = "Sheet1" 'This is the name of the Sheet in your file a = "D56" 'Range of the value you want I'm not sure if you can pull more than cell's value or not ThisWorkbook.Worksheets("Sheet2").Range("F21") = GetValue(p, f, s, a) 'Transfer the value End Sub 

以下是您将需要的function

 Function GetValue(Path, file, sheet, ref) ' Retrieves a value from a closed workbook Dim arg As String ' Make sure the file exists 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