简体   繁体   中英

Implementing delay in data export from Excel to csv file

I have data comming into Excel from a DDE application with a macro. I managed to program the macro so that each data in stored in the next row. Problem: I want to be able to scroll through the data eg to view te values of 5 minutes ago, but I can't because to macro is blocking the workbook. I tried to export the data to a csv file, and view it form there, but I have a problem with the loop saying the file is already open. Anyone have any solution? I'm a real beginner in VBA or programming. Thanks. Here's what i've been trying to run:

Sub DDEread()

' Opens a DDE conversation with the Windmill DDE
' Panel using the Service Name "Windmill" and the
' Topic Name "data"
Dim i As Integer, g As Integer
For i = 2 To 15
' Loop to get 5 values, 1 every second
For g = 0 To 4
ddechan = Excel.DDEInitiate("Windmill", "data")
Cells(g + 1, 4).Value = Excel.DDERequest(ddechan, "Ch0")
Cells(g + 1, 5).Value = Excel.DDERequest(ddechan, "00001")
Application.Wait Now + TimeValue("00:00:01")
Next g

'put the calculated average of 5 cells into other cells to get allways 5 second averaged values
Cells(i, 2).Value = Cells(6, 4)
Cells(i, 3).Value = Cells(6, 5)
Cells(i, 1).Show
Cells(i, 1).Value = Format(Time, "hh:mm:ss")
Cells(i, 1).NumberFormat = "hh:mm:ss"
' Closes the DDE conversation.
Excel.DDETerminate (ddechan)

'Data export to csv file:
Dim myFile As String, cellValue As Variant
myFile = Application.DefaultFilePath & "\PG350data.csv"
Open myFile For Output As #1

cellValue = Cells(i, 2).Value + Cells(i, 3).Value
Write #1, cellValue


Next i
Close #1
End Sub

Refer to the following example of using DoEvents demonstrating how to add responsiveness to the program during execution of a lengthy loop:

   Open "com1" For Input As #1
   Input #1, x
   Do Until x = Chr(13)
   DoEvents
   '...
   '...
   Input #1, x
   Loop

Another example:

   X = Timer()
   Do While X + 10 > Timer()

       DoEvents

   Loop

Detailed explanation here: http://support.microsoft.com/kb/118468

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM