等待在Excel中打开大文件

时间:2015-11-20 01:20:17

标签: excel vba excel-vba loops csv

我一直试图在VBA中遍历一堆大的.csv文件。每个约为50MB。在每次迭代时,我都会打开一个新的CSV来操作数据,但是当.csv打开时,会有一条下载消息说文件正在打开,进度条在VBA等待它完成时总会卡在某个点上。 / p>

实际上.csv是打开的,因为如果我点击"取消"在进度条上,代码继续运行良好但我必须在每次迭代时都进行手动操作。

我的猜测是,当文件没有打开或类似的东西时VBA会进入下一步,所以也许如果我做睡眠或类似的东西它可以工作,但我尝试的东西现在不起作用。 (我已经尝试过Application.EnableEvents = False)。这是我的代码:

Sub GetOptions()

Application.DisplayAlerts = False
Application.EnableEvents = False

Set Dates = Sheets("Dates")
Set Res = Sheets("Options")

Dim dateToday As Date

ETF = "SPY"
nrows = Dates.Cells(Rows.Count, 1).End(xlUp).Row


For i = 708 To nrows

    If Dates.Cells(i, 2).Value = "B" Then
        dateToday = Dates.Cells(i, 1).Value
        dateYear = Year(dateToday)
        stringOpening = "P:\Options Database\CSV\" & dateYear & "\bb_" & dateYear & "_" & GetMonth(dateToday) & "\bb_options_" & Format(dateToday, "yyyymmdd") & ".csv"
        Workbooks.Open stringOpening, UpdateLinks:=0, ReadOnly:=True
        Set Options = Workbooks("bb_options_" & Format(dateToday, "yyyymmdd")).Sheets(1)

        Do things...

        Workbooks("bb_options_" & Format(dateToday, "yyyymmdd")).Close SaveChanges:=False
    End If
Next i


End Sub

1 个答案:

答案 0 :(得分:1)

诀窍是:

  1. 将它们作为读/写文件打开,
  2. 等待Write状态,表明它已完全打开
  3. 将文件设置为只读
  4. 此代码循环,直到文件进入写入状态:

    Sub myWaitForFileOpen()
    Dim wb As Workbook
    Set wb = Application.Workbooks.Open("C:\File.xls")
    
    Do Until wb.ReadOnly = False
        wb.Close
        Application.Wait Now + TimeValue("00:00:01")
        Set wb = Application.Workbooks.Open("C:\File.xls")
    Loop
    'Then the code that needs that Workbook open here!
    'Or Call That other macro here!
    End Sub
    

    这是您的完整代码,它将以读/写方式打开CSV,直到它完全加载,然后将其放回只读:

    Sub GetOptions()
    Dim wB As Workbook
    
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    
    Set Dates = Sheets("Dates")
    Set Res = Sheets("Options")
    
    Dim dateToday As Date
    
    ETF = "SPY"
    nrows = Dates.Cells(Rows.Count, 1).End(xlUp).Row
    
    
    For i = 708 To nrows
        If Dates.Cells(i, 2).Value = "B" Then
            dateToday = Dates.Cells(i, 1).Value
            dateYear = Year(dateToday)
            stringOpening = "P:\Options Database\CSV\" & dateYear & "\bb_" & dateYear & "_" & GetMonth(dateToday) & "\bb_options_" & Format(dateToday, "yyyymmdd") & ".csv"
    
            Set wB = Workbooks.Open(stringOpening, UpdateLinks:=0, ReadOnly:=False)
    
            Do Until wB.ReadOnly = False
                wB.Close
    
                Application.Wait Now + TimeValue("00:00:01")
    
                Set wB = Application.Workbooks.Open("C:\My Files\AAA.xls")
            Loop
            wB.ReadOnly = True
            Set Options = wB.Sheets(1)
    
    
            Do
                'things...
            Loop
    
            wB.Close SaveChanges:=False
        End If
    Next i
    
    End Sub