VBA 用户窗体刷新

标签 vba userform

我有一个单词 VBA 用户窗体,我将其用作排行榜来跟踪 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

但这似乎没有任何作用。如有任何帮助,我们将不胜感激!

最佳答案

您不能使用 Application.OnTime 执行宏以外的任何内容 - 由标准过程模块公开的公共(public)无参数方法。

UserForm_Initialize 不是一个 - 它是一个事件处理程序,用于处理 UserFormInitialize 事件> object.. 每个实例仅在对象初始化时调用一次。您应该永远不需要显式调用事件处理程序。如果您发现自己这样做,则应该敲响警钟,应该悬挂巨大的红旗,某些事情正在做错了

UserForm_Initialize 中的所有内容移至公共(public) 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] 按钮的用户关闭和/或销毁的情况。

关于VBA 用户窗体刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43192983/

相关文章:

excel - 为什么 Excel 2010 VBA 用户窗体文本框字体会根据框架大小而变化?

excel - 在Excel VBA中访问CheckBox的值时如何解决运行时错误424?

javascript - .GetElementsByName.SelectedIndex 明显更改选项但不是以编程方式更改?

vba - 在 Excel VBA 中使用 New 关键字和调用 CreateObject 有什么区别?

vba - 仅适用于一张工作表的 OnKey

text - 使用 ADODB 连接使用 vba 将来自两个不同服务器上的两个不同数据库的两个表左连接

vba - 多次初始化用户窗体

VBA:在运行时通过用户窗体按钮退出宏会在重新启动宏时导致错误 429

vba - 确定单击哪个命令按钮以打开用户窗体

excel - 使用字符串变量作为文本连接