如何优化打开和关闭excel工作簿以提取数据以更快地运行

时间:2014-08-13 13:28:55

标签: excel performance vba excel-vba excel-2007

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

第一种方法如下:

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个文件的文件)但它会爆炸我的任务栏,因为它打开新的工作簿(几乎不可能选择不同的excel工作簿)并且由于某种原因我的代码很容易通过按下移位不止一次或完全按住它来断开,迫使我启动代码。

方法2明显变慢(大约.56秒/ 1052文件的文件),但由于隐藏了Excel应用程序,我的任务栏仍然可用,按shift不会破坏代码。

我想知道的是,有没有办法在不破坏我的任务栏或使用shift停止代码的情况下运行方法1?或者,有没有办法将方法二加速到方法1附近的速度?

*注意:我已经在使用下面的代码来优化我的速度并限制vba /工作簿交互。除了访问工作簿的方法之外,每个场景中的其余代码都是相同的。

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

1 个答案:

答案 0 :(得分:3)

调用使用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 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
相关问题