shaolinfunk
asked on
How do I pause/wait 1 second in Excel VBA?
I am iterating through a for/next loop where each loops retrieves data from a database and outputs data to a .txt file. There are about 3000 iterations (for x = 1 to 3000).
What ends up happening, I think, is that Excel cannot read & write data fast enough to keep up with the for/next loop iterations...and ends up skipping some files and not outputting a .txt file at all. Thus, I am missing some important data files.
How can I "slow down" the for/next loop such that it waits 1 full second before moving onto the next iteration? However, I don't want to "pause" the program because the data will not get read/written/outputted to a .text file if the program is paused. Basically I want to give the macro time to output data before it moves onto the next iteration. How do I do this?
What ends up happening, I think, is that Excel cannot read & write data fast enough to keep up with the for/next loop iterations...and ends up skipping some files and not outputting a .txt file at all. Thus, I am missing some important data files.
How can I "slow down" the for/next loop such that it waits 1 full second before moving onto the next iteration? However, I don't want to "pause" the program because the data will not get read/written/outputted to a .text file if the program is paused. Basically I want to give the macro time to output data before it moves onto the next iteration. How do I do this?
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
debug.print the data - then take a look at what excel is writing. If it is a timing issue, then you will see incorect data. If it is a file issue (disk full, no permissions, not closing file(s) ) then you would see correct data in the debug window
How are you retrieving the data? If you are using an asynchronous technique you are going to have timing problems and inserting a pause will only start to solve the problem.
A better solution (and bulletproof) is to us a synchronous technique such as using the ADODB interface. Your code will not continue until the DB command is complete.
Here is a tutorial on using ADODB to interface with a database.
The following text and sample code illustrates how to:
-> open a database connection
-> use a stored procedure to perform a query
-> execute any SQL command against a database
-> open a recordset using a custom query
-> open a recordset using a table name
-> check for an empty recordset
-> read all records in a recordset
-> add a record to a recordset
-> delete a record from a recordset
-> copy a recordset with headers to a worksheet
-> close a recordset and database
This sample code, except for Open database method, can be used with any database such as Access, SQL Server, or Oracle. When using a database, most interaction happens via a recordset. Data is manipulated almost entirely using Recordset objects. Any number of Recordset objects can be created and used at the same time - each representing a different query or the same query. Different Recordset objects can access the same tables, queries, and fields without conflicting.
After opening a Recordset the Recordset can contain zero or more records. One record in the Recordset is always the current record except when the Recordset BOF or EOF property is true in which case no record is the current record. The current record is the record that is affected by any record-specific methods. To move amongst the records in a Recordset use the MoveNext, MovePrevious, MoveLast, and MoveFirst Recordset methods. A specific record can be made the current record by setting the AbsolutePosition property to the index number of the desired record. Fields in the current record are access as illustrated below.
Value = MyRecordset!Field1
MyRecordset!Field2 = Value + 1
When the current record is changed use the Update method to apply the changes to the database. Use the Add method to add a new record and the Delete method to delete the current record. The Add method can be used even if the query returns an empty recordset.
Caution about using the RecordCount method: The RecordCount for a serverside recordset may return a -1. This occurs with ActiveX Data Objects (ADO) version 2.0 or later when the CursorType is adOpenForwardonly or adOpenDynamic and when with ADO 1.5 only when the cursortype is adOpenForwardonly. To get around this problem use either adOpenKeyset or adOpenStatic as the CursorType for server side cursors or use a client side cursor. Client side cursors use only adOpenStatic for CursorTypes regardless of which CursorType is selected.
Before writing any ADODB code the data objects library "Microsoft ActiveX Data Objects x.x Library" must be referenced in the VBA project (Tools->References).
For additional information on the ADODB interface see the MSDN pages at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmscadoapireference.asp
Sample code:
Dim MyDatabase As ADODB.Connection
Dim MyCommand As ADODB.Command
Dim MyRecordset As ADODB.RecordSet
Dim Column As Long
' Open database connection
Set MyDatabase = New ADODB.Connection
MyDatabase.CursorLocation = adUseClient
MyDatabase.Open "Provider=Microsoft.Jet.OL EDB.4.0; Data Source='C:\full\path\to\da tabase.mdb '; User Id=admin; Password=;"
' For more information about Open syntax:
' http://msdn.microsoft.com/en-us/library/ms808201.aspx
' Additional help constructing connection strings can be found at http://www.connectionstrings.com/
' Query database using stored procedure (requires command object)
Set MyCommand = New ADODB.Command
Set MyCommand.ActiveConnection = MyDatabase
MyCommand.CommandText = "qrySomeQuery" ' <- name of procedure
MyCommand.CommandType = adCmdStoredProc
With MyCommand
.Parameters.Refresh
.Parameters.Append .CreateParameter("QueryTex tParam", adVarChar, adParamInput, 10, StringValue)
.Parameters.Append .CreateParameter("QueryTex tParam", adDouble, adParamInput, , DoubleValue)
.Parameters.Append .CreateParameter("QueryLon gParam", adBigInt, adParamInput, , LongValue)
.Parameters.Append .CreateParameter("QueryDat eParam", adDate, adParamInput, , DateValue)
.Parameters.Append .CreateParameter("QueryDat eTimeStamp Param", adDBTimeStamp, adParamInput, , DateTimeValue)
.Parameters.Append .CreateParameter("BooleanP aram", adBoolean, adParamInput, , BooleanValue)
' For more information about CreateParameter syntax:
' http://msdn.microsoft.com/en-us/library/ms808298.aspx
End With
' Open recordset using command object
Set MyRecordset = New ADODB.Recordset
MyRecordset.Open MyCommand, , adOpenDynamic, adLockPessimistic
' For more information about Open method syntax:
' http://msdn.microsoft.com/en-us/library/ms808656.aspx
' Build a custom query using command object
Set MyCommand = New ADODB.Command
With MyCommand
Set .ActiveConnection = MyDatabase
.CommandType = adCmdText
.CommandText = "SELECT * From tblMyTable WHERE (tblMyTable.MyID = 1)"
End With
MyRecordSet.Open MyCommand, , adOpenDynamic, adLockReadOnly
' Execute any SQL statement
MyDatabase.Execute "INSERT INTO TableName (Field1, Field2) VALUES ('" & Range("A1").Value & "','" & Range("A2").Value & "')"
' Open a recordset by specifying specific table (no query)
MyRecordset.Open "TableName", MyDatabase, adOpenDynamic, adLockPessimistic
' Open a recordset by specifying query without using command object
MyRecordset.Open "SELECT * FROM MyTable", MyDatabase, adOpenDynamic, adLockPessimistic
' Test for no records
If MyRecordset.BOF And MyRecordset.EOF Then
MsgBox "No records in table"
End If
' Determine total records (see notes above about inconsistencies with the RecordCount method)
MsgBox "Total records: " & MyRecordset.RecordCount
' Look at all records in record set
While Not MyRecordset.EOF
MsgBox "Record number: " & MyRecordset.AbsolutePositi on
MyRecordset.MoveNext
Wend
' Find a specific record given a field value
MyRecordset.MoveFirst
MyRecordset.Find "ID='ABC123'"
If Not MyRecordset.BOF And Not MyRecordset.EOF Then
MyRecordset!Field1 = "Match Found"
MyRecordset.Update
End If
' Copy the entire recordset to a worksheet (this technique does not copy field names)
Sheets("Sheet1").[A2].Copy FromRecord set MyRecordset
' Create headers and copy data
With Sheets("Sheet1")
For Column = 0 To MyRecordset.Fields.Count - 1
.Cells(1, Column + 1).Value = MyRecordset.Fields(Column) .Name
Next
.Range(.Cells(1, 1), .Cells(1, MyRecordset.Fields.Count)) .Font.Bold = True
.Cells(2, 1).CopyFromRecordset MyRecordset
End With
' Update current record
MyRecordset!Field1 = "Some data"
MyRecordset!Field2 = "Some more data"
MyRecordset.Update
' Move specific fields from current record to worksheet
With Sheets("Sheet1")
Cells(Row, "A") = MyRecordset!Field1
Cells(Row, "B") = MyRecordset!Field2
End With
' Add new record and set field values
MyRecordset.AddNew
MyRecordset!Field1 = "Some data"
MyRecordset.Update
' Update an existing record or add it if it does not exist
MyRecordset.MoveFirst
MyRecordset.Find "Field1='"& SourceSheet.Cells(Row, "A") & "'"
If MyRecordset.BOF Or MyRecordset.EOF Then
MyRecordset.AddNew
End If
MyRecordset!Field1 = SourceSheet.Cells(Row, "A")
MyRecordset!Field2 = SourceSheet.Cells(Row, "B")
MyRecordset.Update
' Delete current record
MyRecordset.Delete
' Close recordset
MyRecordset.Close
' Close database
MyDatabase.Close
Kevin
A better solution (and bulletproof) is to us a synchronous technique such as using the ADODB interface. Your code will not continue until the DB command is complete.
Here is a tutorial on using ADODB to interface with a database.
The following text and sample code illustrates how to:
-> open a database connection
-> use a stored procedure to perform a query
-> execute any SQL command against a database
-> open a recordset using a custom query
-> open a recordset using a table name
-> check for an empty recordset
-> read all records in a recordset
-> add a record to a recordset
-> delete a record from a recordset
-> copy a recordset with headers to a worksheet
-> close a recordset and database
This sample code, except for Open database method, can be used with any database such as Access, SQL Server, or Oracle. When using a database, most interaction happens via a recordset. Data is manipulated almost entirely using Recordset objects. Any number of Recordset objects can be created and used at the same time - each representing a different query or the same query. Different Recordset objects can access the same tables, queries, and fields without conflicting.
After opening a Recordset the Recordset can contain zero or more records. One record in the Recordset is always the current record except when the Recordset BOF or EOF property is true in which case no record is the current record. The current record is the record that is affected by any record-specific methods. To move amongst the records in a Recordset use the MoveNext, MovePrevious, MoveLast, and MoveFirst Recordset methods. A specific record can be made the current record by setting the AbsolutePosition property to the index number of the desired record. Fields in the current record are access as illustrated below.
Value = MyRecordset!Field1
MyRecordset!Field2 = Value + 1
When the current record is changed use the Update method to apply the changes to the database. Use the Add method to add a new record and the Delete method to delete the current record. The Add method can be used even if the query returns an empty recordset.
Caution about using the RecordCount method: The RecordCount for a serverside recordset may return a -1. This occurs with ActiveX Data Objects (ADO) version 2.0 or later when the CursorType is adOpenForwardonly or adOpenDynamic and when with ADO 1.5 only when the cursortype is adOpenForwardonly. To get around this problem use either adOpenKeyset or adOpenStatic as the CursorType for server side cursors or use a client side cursor. Client side cursors use only adOpenStatic for CursorTypes regardless of which CursorType is selected.
Before writing any ADODB code the data objects library "Microsoft ActiveX Data Objects x.x Library" must be referenced in the VBA project (Tools->References).
For additional information on the ADODB interface see the MSDN pages at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmscadoapireference.asp
Sample code:
Dim MyDatabase As ADODB.Connection
Dim MyCommand As ADODB.Command
Dim MyRecordset As ADODB.RecordSet
Dim Column As Long
' Open database connection
Set MyDatabase = New ADODB.Connection
MyDatabase.CursorLocation = adUseClient
MyDatabase.Open "Provider=Microsoft.Jet.OL
' For more information about Open syntax:
' http://msdn.microsoft.com/en-us/library/ms808201.aspx
' Additional help constructing connection strings can be found at http://www.connectionstrings.com/
' Query database using stored procedure (requires command object)
Set MyCommand = New ADODB.Command
Set MyCommand.ActiveConnection
MyCommand.CommandText = "qrySomeQuery" ' <- name of procedure
MyCommand.CommandType = adCmdStoredProc
With MyCommand
.Parameters.Refresh
.Parameters.Append .CreateParameter("QueryTex
.Parameters.Append .CreateParameter("QueryTex
.Parameters.Append .CreateParameter("QueryLon
.Parameters.Append .CreateParameter("QueryDat
.Parameters.Append .CreateParameter("QueryDat
.Parameters.Append .CreateParameter("BooleanP
' For more information about CreateParameter syntax:
' http://msdn.microsoft.com/en-us/library/ms808298.aspx
End With
' Open recordset using command object
Set MyRecordset = New ADODB.Recordset
MyRecordset.Open MyCommand, , adOpenDynamic, adLockPessimistic
' For more information about Open method syntax:
' http://msdn.microsoft.com/en-us/library/ms808656.aspx
' Build a custom query using command object
Set MyCommand = New ADODB.Command
With MyCommand
Set .ActiveConnection = MyDatabase
.CommandType = adCmdText
.CommandText = "SELECT * From tblMyTable WHERE (tblMyTable.MyID = 1)"
End With
MyRecordSet.Open MyCommand, , adOpenDynamic, adLockReadOnly
' Execute any SQL statement
MyDatabase.Execute "INSERT INTO TableName (Field1, Field2) VALUES ('" & Range("A1").Value & "','" & Range("A2").Value & "')"
' Open a recordset by specifying specific table (no query)
MyRecordset.Open "TableName", MyDatabase, adOpenDynamic, adLockPessimistic
' Open a recordset by specifying query without using command object
MyRecordset.Open "SELECT * FROM MyTable", MyDatabase, adOpenDynamic, adLockPessimistic
' Test for no records
If MyRecordset.BOF And MyRecordset.EOF Then
MsgBox "No records in table"
End If
' Determine total records (see notes above about inconsistencies with the RecordCount method)
MsgBox "Total records: " & MyRecordset.RecordCount
' Look at all records in record set
While Not MyRecordset.EOF
MsgBox "Record number: " & MyRecordset.AbsolutePositi
MyRecordset.MoveNext
Wend
' Find a specific record given a field value
MyRecordset.MoveFirst
MyRecordset.Find "ID='ABC123'"
If Not MyRecordset.BOF And Not MyRecordset.EOF Then
MyRecordset!Field1 = "Match Found"
MyRecordset.Update
End If
' Copy the entire recordset to a worksheet (this technique does not copy field names)
Sheets("Sheet1").[A2].Copy
' Create headers and copy data
With Sheets("Sheet1")
For Column = 0 To MyRecordset.Fields.Count - 1
.Cells(1, Column + 1).Value = MyRecordset.Fields(Column)
Next
.Range(.Cells(1, 1), .Cells(1, MyRecordset.Fields.Count))
.Cells(2, 1).CopyFromRecordset MyRecordset
End With
' Update current record
MyRecordset!Field1 = "Some data"
MyRecordset!Field2 = "Some more data"
MyRecordset.Update
' Move specific fields from current record to worksheet
With Sheets("Sheet1")
Cells(Row, "A") = MyRecordset!Field1
Cells(Row, "B") = MyRecordset!Field2
End With
' Add new record and set field values
MyRecordset.AddNew
MyRecordset!Field1 = "Some data"
MyRecordset.Update
' Update an existing record or add it if it does not exist
MyRecordset.MoveFirst
MyRecordset.Find "Field1='"& SourceSheet.Cells(Row, "A") & "'"
If MyRecordset.BOF Or MyRecordset.EOF Then
MyRecordset.AddNew
End If
MyRecordset!Field1 = SourceSheet.Cells(Row, "A")
MyRecordset!Field2 = SourceSheet.Cells(Row, "B")
MyRecordset.Update
' Delete current record
MyRecordset.Delete
' Close recordset
MyRecordset.Close
' Close database
MyDatabase.Close
Kevin
ASKER
most detailed response i've ever gotten on EE. thanks!
Open in new window