I am trying to write a macro in VB for an Excel spreadsheet which is executed in specific intervals which are defined by a value (in Hz) contained in the spreadsheet itself. My problem is that the code I found for accomplishing an automatic macro in this way appears to only allow for second accuracy, so any frequencies above 1Hz are not possible. I would like to be able to get up to around 10Hz if possible, which would require millisecond accuracy.
I am new to VB, so I do not know much about it. Here is the code:
Sub Macro2()
Range("K1").Select
Dim f As Single
f = ActiveCell.Value
Dim t As Integer
t = 1 / f
dTime = Now + TimeSerial(0, 0, t)
Application.OnTime dTime, "Macro2"
Range("J1").Select
Dim c As Integer
c = ActiveCell.Value
c = c Xor 1
ActiveCell.Value = c
End Sub
Is there any way to get Millisecond accuracy using this method?
Excel does not work in anything less than whole seconds.
There are a couple of issues with your code:
You define
Dim t As Integerand go on to assignt = 1 / fwhich means that for any value offgreater than one,twill be zero (because it’s constrained to be an integer).TimeValue()can only work in whole seconds, so it doesn’t matter whethertis a fraction or not becauseTimeValue()will discard any fractional part.The macro will run with
tbeing zero, but it’s uncontrolled and irregular. I suspect that is part of the reason that Excel VBA doesn’t work in milliseconds: the execution of VBA code just isn’t accurate enough.Unfortunately, because VBA can’t work in milliseconds, I can’t suggest a way of making it do so.