在Excel中向宏添加进度条

时间:2013-12-22 02:13:22

标签: excel-vba vba excel

我有一个非常简单的宏,它将刷新与按钮联系起来。它只是单击按钮,它刷新工作簿中的所有外部连接(xml和Web)。但是,我正在尝试在消息栏中添加进度条或状态消息。

现在很简单:

Sub refreshAll()
    ActiveWorkbook.refreshAll
End Sub

它做了它应该做的事情,现在我只是想要一些方法来告诉它有多远(并让进程在后台运行。我想把它改成计算有多少连接的东西,然后通过刷新每个连接,同时在状态栏中计算出来。

如:“300中的15个完成20%”

它只是简单地计算,因为它经历了更新吧。我不知道是否有办法使用refreshAll更新栏,或者如果我必须循环并刷新它们计数。有什么想法吗?

编辑:

我的工作大部分都是:

Sub refreshAll()

    Dim con As String
    Dim cLen As Integer
    Dim i As Integer
    Dim pInt As Double
    Dim percent As String
    cLen = ActiveWorkbook.Connections.count
    i = 0

    Do
        con = "Connection" & i
        pInt = i / cLen
        percent = FormatPercent(pInt, 0)
        ActiveWorkbook.Connections(con).Refresh
        Application.StatusBar = "Updated " & i & " of " & cLen & " | " & percent & " Complete"
        i = i + 1
    Loop While i < cLen
    Application.StatusBar = "Update Finished"

End Sub

问题在于一切都按预期工作,它计算正确的连接数,并且在状态栏中它打印得像它应该但它会在一秒钟内完成,而不会实际更新任何连接。如果我按下“全部刷新”按钮,刷新数据大约需要15秒,如果我点击我创建的按钮,它只是拉开而不刷新。

2 个答案:

答案 0 :(得分:0)

为每个连接关闭Enable background refresh中的Data > Connections。另外,请尝试使用For - 循环而不是Do-While循环(请参阅以下代码)。

Sub RefreshAll()

    Dim con As String
    Dim cLen As Long
    Dim Iter As Long
    Dim pInt As Double
    Dim percent As String
    cLen = ActiveWorkbook.Connections.Count - 1

    For Iter = 0 To cLen
        con = "Connection" & Iter
        pInt = Iter / (cLen + 1)
        percent = FormatPercent(pInt, 0)
        ActiveWorkbook.Connections(con).Refresh
        Application.StatusBar = "Updated " & Iter & " of " & (cLen + 1) & " | " & percent & " Complete"
    Next Iter

    Application.StatusBar = "Update Finished"

End Sub

如果有帮助,请告诉我们。

答案 1 :(得分:0)

我还不清楚你的连接命名方案。这将使用索引逐步更新工作簿中的所有连接。状态栏已更新。我将消息移到了更新之前,因为人眼更有可能看到它:

Sub RefreshAllConnections()
Dim con As String
Dim cLen As Long
Dim Iter As Long
Dim pInt As Double
Dim percent As String
cLen = ActiveWorkbook.Connections.Count

For Iter = 1 To cLen
    pInt = Iter / cLen
    percent = FormatPercent(pInt, 0)
    With ActiveWorkbook.Connections(Iter)
       Application.StatusBar = "Updating " & Iter & " of " & cLen & " | " & percent & " Complete"
        .Refresh
    End With
Next Iter

Application.StatusBar = False
End Sub