gpt4 book ai didi

VBA 用户窗体刷新

转载 作者:行者123 更新时间:2023-12-02 03:57:48 26 4
gpt4 key购买 nike

我有一个单词 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com