vba 中的进度条

问题描述 投票:0回答:1

我正在使用一个需要很长时间才能执行的宏(>1 分钟),我想通过添加进度条来改进它。 我遵循了多个教程,这些教程都说创建用户表单,添加元素并修改其宽度(如下所示:https://www.excel-easy.com/vba/examples/progress-indicator.html)。

我尝试过类似的方法,但不起作用。

这是我的代码:

' Montrer la barre d'avancement
    ProgressBar.Show
    
    For i = 1 To catia.Documents.Count ' Parcourir l'ensemble des documents en mémoire
        ' À Chaque tour de boucle For, mettre à jour la barre de progression
        CurrentpctComplete = Int(i / catia.Documents.Count)
        BarProgress (CurrentpctComplete)
    
        ' Some stuff with CATIA Documents
    Next i

这是我的更新功能

Sub BarProgress(pctComplete As Single)
    ProgressBar.Text.Caption = pctComplete & "% Completed"
    ProgressBar.Bar.Width = pctComplete * 2
    ProgressBar.Repaint
    DoEvents
End Sub

结果是在 For 循环的开始处显示弹出窗口,然后一切都冻结了。仅当我单击弹出窗口的红叉时,程序才会继续。

我尝试在 for 循环中移动更新片段,但它什么也没做*。

excel vba for-loop progress-bar
1个回答
0
投票

没有发生任何事情的原因是

currentpctComplete
始终为 0(除非到达最后一个文档),因为只要 i 小于文档计数,
Int(i / catia.Documents.Count)
就是 0。

如果要显示百分比,请使用

Dim CurrentpctComplete As Long
CurrentpctComplete = Int(100 * i / catia.Documents.Count)

现在

CurrentpctComplete
将获得 0 到 100 之间的值 - 您应该传递一个整数(使用数据类型
Long
)。

Sub BarProgress(pctComplete As Long)
    ...
End Sub

或者将分数传递给进度条窗体,让窗体决定如何处理它:

Dim CurrentpctComplete As Double
CurrentpctComplete = i / catia.Documents.Count

现在

CurrentpctComplete
将获得 0 到 1 之间的值 - 使用 Single 或 Double 作为数据类型。

Sub BarProgress(complete As Double)
    Dim pctComplete as Long
    pctComplete = CLng(100 * complete)
    (...)
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.