Wait for CSV file to open?

前端 未结 1 541
Happy的楠姐
Happy的楠姐 2021-01-22 12:15

I am trying to download and open a CSV file using VBA in Excel. When I step through using the debugger my code works fine but when I try to run it normally it won\'t work, it is

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 13:00

    Usually such behavior happens not because of the code logic but because of interrupts. Depending on the nature of your environment it could be one of two things

    • some background refreshing process is getting executed sometime in between your code execution time causing some issues. e.g. in a financial services environment, your Bloomberg API could be doing its timely BlpUpdate event
    • your code blocks up a large chunk of time and causes unexpected behavior because event which was triggered during your loop was blocked too long waiting for your code to complete on the main thread.

    So you need to try the following two solutions, one of which should work

    For the second problem, inside your

    Do While Condition
    ' ... your code ...
    Loop
    

    add a line of code that checks for and clears any pending Event queues, making it...

    Do While Condition
    DoEvents     ' either put it at the start or at the end of your code
    ' ... your existing code ...
    Loop
    

    This will give the system some 'breathing space' to wrap up pending events. You'll need to experiment with the location of your DoEvents code.

    For the first problem, you can try enclosing your entire loop within an Event Protected area of code, to ensure it finishes running before anything disturbs it.

    Application.EnableEvents = False
    
    'your loop and other code comes here
    
    Application.EnableEvents = True
    

    Once again, you might need a bit of trial and error to see how much of the code needs to be thrown into the Event-free zone before it works as expected.

    0 讨论(0)
提交回复
热议问题