简体   繁体   English

带有用户表单的 Excel VBA 进度条

[英]Excel VBA Progress Bar with userform

I'm trying to learn how to use a progress bar with a userform.我正在尝试学习如何在用户表单中使用进度条。

The problem I have, with my code, is that it displays the progress bar after running the loop;我的代码遇到的问题是它在运行循环后显示进度条; it should be running the loop while showing the progress bar instead like 10%...20%...30%...40%......100%.它应该在显示进度条的同时运行循环,而不是像 10%...20%...30%...40%...100%。

Can anyone help me fix my code to achieve this?谁能帮我修复我的代码以实现这一目标?

'-----Below is loop-----------------------------------------------------
Sub looprange()
   Dim r As Range
'----------loop thru 0 to 9 ---------------
   For Each r In Sheet6.Range("j2", Range("j" & Rows.Count).End(xlUp))

      Sheet6.Range("i2").Value = r.Value

      ActiveWindow.ScrollRow = 11
      Application.CutCopyMode = False

      Call print_jpeg

   Next r

   MsgBox "done"

End Sub

-- ——

'--------Below is vba code in userform :------------
Private Sub UserForm_Activate()

    Dim remainder As Long
    Dim i As Long, j As Long

    Call looprange

    remainder = 0

    For i = 1 To 200

        UserForm1.Label2.Width = UserForm1.Label2.Width + 1

        If i Mod 2 = 0 Then
            remainder = remainder + 1
            UserForm1.Caption = remainder & ” % complete”
            UserForm1.Label2.Caption = remainder & “%”
        End If

        For j = 1 To 600

            DoEvents

        Next j

    Next i

    MsgBox “Loading of program complete.”

    Unload UserForm1

End Sub

I believe a true status bar is not included in standard VBA (without references), however you can abuse a label control.我相信标准 VBA 中不包含真正的状态栏(没有引用),但是您可以滥用标签控件。 Be aware that this method trades performance for user clarity (the user can see that the application is working, but it is slower than the same application without the status bar)请注意,此方法为了用户的清晰度而牺牲了性能(用户可以看到应用程序正在运行,但它比没有状态栏的同一个应用程序要慢)

Simply add three labels, one for status text, one for the actual moving bar and one for full bar border.只需添加三个标签,一个用于状态文本,一个用于实际移动条,一个用于完整条边框。 And format them to fit your application (see image below):并格式化它们以适合您的应用程序(见下图): 可视化 VBA 进度条设置的图像

Code below:代码如下:

Private Sub cbStart_Click()
 one_percent_bar_width = lLoadBar.Width / 100 'width of one percent of the total loading bar
 max_numbers = 1000 'only for demo purpose

 Me.lLoadingBar.Visible = True
 For i = 0 To max_numbers 'your loop here

     'your code here

   percentage = i / max_numbers * 100 'calculation of progress, replace i and max_numbers to fit your loop
   Me.lStatus.Caption = percentage & "% complete" 'status percentage text
   Me.lLoadingBar.Width = percentage * one_percent_bar_width 'width of actual blue bar
   DoEvents 'slows down code but only way to make the bar visibly move, tradeoff between user clarity and speed
 Next i 'edit to fit your loop
 Me.lStatus.Caption = "Complete!" 'adjust status to whatever you want
End Sub

Private Sub UserForm_Initialize()
 Me.lLoadingBar.Visible = False 'hide the small blue bar
 Me.lStatus.Caption = "Progress not started" 'adjust status to whatever you want
End Sub

There are a few issues with your code, but to focus on the Progress Bar part, I'll share an example of one way to handle a progress bar in Excel (using the built-in status bar).您的代码存在一些问题,但为了关注进度条部分,我将分享一个示例,说明在 Excel 中处理进度条的一种方法(使用内置状态栏)。

Instead of actually doing anything useful, this example is pausing for a split second between loops, but reports the status on the status bar.) Hopefully it will give you some ideas.这个例子实际上并没有做任何有用的事情,而是在循环之间暂停一秒钟,但在状态栏上报告状态。)希望它会给你一些想法。

Sub ProgressBarTest()

    Const LoopsToRun = 500
    Dim z As Integer

    For z = 1 To LoopsToRun
        'put a random number in A1
        Range("A1") = Int(Rnd() * 100) + 1

        'update status bar
        Application.StatusBar = "Progress: " & Format((z / LoopsToRun), "0.0%")

        'pause for .3 seconds (instead of pausing, you'd run your actual procedure here)
        Pause (0.1)
    Next z

    Application.StatusBar = "Complete!"

End Sub

Sub Pause(sec As Single)
    'pauses for [sec] second
    Dim startTime As Single
    startTime = Timer
    Do While Timer < startTime + sec
        DoEvents
    Loop
End Sub

More info here and here .更多信息在这里这里

VBA has a progress bar control that can be added to forms. VBA 有一个可以添加到表单的进度条控件 While you are learning, you can simply add this control to the form and then update that control during the loop where you are doing the useful form functions.在学习过程中,您可以简单地将此控件添加到表单中,然后在执行有用表单功能的循环中更新该控件。 The progress bar controls includes useful properties such as min and max.进度条控件包括有用的属性,例如 min 和 max。

If you are doing multiple things in your form, you can update a label to tell the user what is progressing as well as the amount of progress.如果您在表单中执行多项操作,您可以更新标签以告诉用户正在进行的工作以及进度。

[More advanced] In some of my previous work, I have set up VBA routines to run in the background and created a progress bar form using events. [更高级] 在我之前的一些工作中,我设置了在后台运行的 VBA 例程,并使用事件创建了一个进度条表单。 This allows for a more sophisticated view with progress statements as well as a percentage run.这允许使用进度报表和百分比运行的更复杂的视图。 But the basis of this form is still the progress bar control.但这种形式的基础仍然是进度条控件。 While using events is more complicated it allowed me to make a more general progress bar form that can be used by any of my vba functions and these functions are then unaffected by any changes I make to the form because the events act as a kind of standard interface.虽然使用事件更复杂,但它允许我制作一个更通用的进度条表单,可供我的任何 vba 函数使用,然后这些函数不受我对表单所做的任何更改的影响,因为事件充当一种标准界面。

Update from a comment by @MathieuGuindon: "The control is actually a VB6 control and will only work in a 32-bit VBA host with the .OCX properly registered, which is getting more and more challenging to do with the more recent Windows versions; referencing and using these controls in VBA7 is heavily discouraged."来自@MathieuGuindon的评论更新:“该控件实际上是一个 VB6 控件,只能在正确注册 .OCX 的 32 位 VBA 主机中工作,这在更新的 Windows 版本中变得越来越具有挑战性;强烈建议不要在 VBA7 中引用和使用这些控件。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM