VBA定时器给一切都是0

我有一个计时器,计算执行相同计算的数据types之间的执行时间差异。

这是macros:

Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Sub Function1_Var_RandNumCounter() Dim Var_RandNum_X As Variant, Var_RandNum_Y As Variant, Count As Variant For Count = 1 To Count = 1000000000 Var_RandNum_X = Rnd(Now) ' Get rnd vals based on Now, built-in VBA property Var_RandNum_Y = Rnd(Now) Next Count Select Case IsNull("A2") Case True Cells.Clear Set target_sheet = ActiveSheet target_sheet.Range("A2").Value = -t Case False Set target_sheet = ActiveSheet target_sheet.Range("A2").Value = -t End Select 'MsgBox GetTickCount - t, , "Milliseconds" Call Function1_Dec_RandNumCounter End Sub Sub Function1_Dec_RandNumCounter() Dim Count, Var_RandNum_X, dec_RandNum_X, Var_RandNum_Y, dec_RandNum_Y dec_RandNum_X = CDec(Var_RandNum_X) dec_RandNum_Y = CDec(Var_RandNum_Y) ' convert these vals to decimals For Count = 1 To Count = 1000000000 dec_RandNum_X = Rnd(Now) ' Get rnd vals based on Now, built-in VBA property dec_RandNum_Y = Rnd(Now) Next Count Select Case IsNull("B2") Case True Cells.Clear Set target_sheet = ActiveSheet target_sheet.Range("B2").Value = -t Case False Set target_sheet = ActiveSheet target_sheet.Range("B2").Value = -t End Select 'MsgBox GetTickCount - t, , "Milliseconds" Call Function1_Int_RandNumCounter End Sub Sub Function1_Int_RandNumCounter() Dim Count, Int_RandNum_X, Int_RandNum_Y For Count = 1 To Count = 1000000000 Int_RandNum_X = Rnd(Now) Int_RandNum_Y = Rnd(Now) Next Count Select Case IsNull("C2") Case True Cells.Clear Set target_sheet = ActiveSheet target_sheet.Range("C2").Value = -t Case False Set target_sheet = ActiveSheet target_sheet.Range("C2").Value = -t End Select 'MsgBox GetTickCount - t, , "Milliseconds" Call Function1_Double_RandNumCounter End Sub Sub Function1_Double_RandNumCounter() Dim Count, Dbl_RandNum_X, Dbl_RandNum_Y For Count = 1 To Count = 1000000000 Dbl_RandNum_X = Rnd(Now) Int_RandNum_Y = Rnd(Now) Next Count Select Case IsNull("D2") Case True Cells.Clear Set target_sheet = ActiveSheet target_sheet.Range("D2").Value = -t Case False Set target_sheet = ActiveSheet target_sheet.Range("D2").Value = -t End Select 'MsgBox GetTickCount - t, , "Milliseconds" End Sub Sub Function2_BarGraph() 'Put all of these vals in a 2D bar graph End Sub 

当我运行这个我给所有的0值。 即使增加小数点位数,时间也是0.00000s。 我该怎么办呢?

两件事情:

  1. VB中的variables不是键入的(是Variant),除非你声明它们是一个具有AS子句的特定types。

     Dim Count AS Long, Int_RandNum_X AS Integer, Int_RandNum_Y AS Integer 

AS必须用于每个variables,下面的语句只会将Int_RandNum_Y声明为一个整数,并将Int_RandNum_X作为一个变体:

  Dim Count AS Long, Int_RandNum_X, Int_RandNum_Y AS Integer 
  1. 你永远不会把值赋给't'。 它是在你的MsgBox调用中声明的。 你应该申报

     Dim t as Double 

在例程的早期,然后将当前时间分配给它

  t = Timer 

然后,你可以用几秒钟的时间获得stream逝的时间

  t = Timer - t