VBA UserForm刷新

时间:2017-04-03 19:41:56

标签: vba userform

我有一个单词VBA UserForm,我将其用作排行榜,以便在更新时跟踪SQL查询的结果。有没有办法在每10分钟启动一次表格后自动刷新?我试过这个:

Private Sub UserForm_Initialize()
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim AgingSQL As String

cnn.ConnectionString = "DATABASE INFO"
cnn.Open

AgingSQL = "SQL QUERY"
rst.Open AgingSQL, cnn
rst.MoveFirst
With UserForm1.AgingLeaderboard -- List Box I am using to display info
     .Clear
     Do
        .AddItem
        .List(i, 0) = rst![StatusBy]
        .List(i, 1) = rst![Count]
        i = i + 1
        rst.MoveNext
    Loop Until rst.EOF
End With
rst.Close
**Call Refresh**
End Sub

Sub Refresh()
   Application.OnTime Now + TimeValue("00:00:10"), "UserForm_Initialize"
End Sub

但这似乎没有做任何事情。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:3)

您无法使用Application.OnTime执行宏以外的任何操作 - 由标准的程序模块公开的公共无参数方法。

UserForm_Initialize不是 - 它是一个事件处理程序,它处理Initialize对象的UserForm事件..它只被调用每个实例一次,当对象,初始化时。您应该从不,需要显式调用事件处理程序。如果你发现自己这样做了,闹铃应该响起,巨大的红旗应该飞,正在做的事情非常错误

UserForm_Initialize中的所有内容转移到公开RefreshLeaderboard方法 - 您无需处理Initialize

Option Explicit

Public Sub RefreshLeaderboard()
    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim AgingSQL As String

    cnn.ConnectionString = "DATABASE INFO"
    cnn.Open

    AgingSQL = "SQL QUERY"
    rst.Open AgingSQL, cnn
    rst.MoveFirst
    With AgingLeaderboard '-- note: was With UserForm1.AgingLeaderBoard

         .Clear
         Do
            .AddItem
            .List(i, 0) = rst![StatusBy]
            .List(i, 1) = rst![Count]
            i = i + 1
            rst.MoveNext
        Loop Until rst.EOF
    End With
    rst.Close    
End Sub

现在您需要一个可以安排的宏,它可以访问表单实例。

Option Explicit
Private leaderboardForm As MyAwesomeForm ' whatever the UserForm class name is

Public Sub ShowLeaderboard()
    Set leaderboardForm = New MyAwesomeForm
    ScheduleNextRefresh
    leaderboardForm.Show 'vbModal?
    'Set leaderBoardForm = Nothing '' only if the form was modal and not X'd-out
End Sub

Public Sub ScheduleNextRefresh()
    If Not leaderboardForm Is Nothing Then
        leaderboardForm.RefreshLeaderboard
        Application.OnTime Now + TimeValue("00:00:10"), "ScheduleNextRefresh"
    End If
End Sub

您可能希望在表单的代码隐藏中处理QueryClose事件,以便处理由单击[X]按钮的用户关闭和/或销毁它。