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

110*_*gon 7 excel performance 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
Run Code Online (Sandbox Code Playgroud)

第二个是这样的:

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
Run Code Online (Sandbox Code Playgroud)

我的困境是这样的:

方法 1 更快(对于 1052 个文件,大约 0.35 秒/文件)但它在打开新工作簿时会爆炸我的任务栏(使得几乎不可能选择不同的 excel 工作簿)并且由于某种原因,我的代码可以通过按轻松破解多次移动或完全按住它,迫使我重新开始编写代码。

方法 2 明显较慢(对于 1052 个文件,每个文件大约需要 0.56 秒),但由于隐藏了 excel 应用程序,我的任务栏仍然可用,按 shift 不会破坏代码。

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

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

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
End With
Run Code Online (Sandbox Code Playgroud)

小智 5

调用GetValue使用的函数的示例代码ExecuteExcel4Macro

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
Run Code Online (Sandbox Code Playgroud)

GetValue 功能:

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
Run Code Online (Sandbox Code Playgroud)