用户窗体中的进度栏

时间:2018-08-13 11:48:38

标签: vba excel-vba word-vba

我正在尝试在用户窗体中创建一个进度条,而不是使用单独的进度条,因为就其顶部或背景而言,这似乎并不可靠。因此,进度条运行良好,但是对于进度条进行的每次更新,它都会重新绘制整个用户窗体。是否可以只刷新进度条而不是整个用户表单?

我当前的代码看起来像这样:

Public Sub progress(pctCompl As Single)
    Me.Text.caption = Format(pctCompl, "##") & "% Completed"
    Me.Bar.width = Round(pctCompl * 10, 5)
    If Me.Bar.width Mod 20 = 0# Then
        Me.Repaint
    End If
    DoEvents
End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

在对象浏览器中,当在Repaint库中搜索MSForm时,将找到UserForm,但也会找到Frame。因此,如果您想直接使用用户窗体上的进度,则可以尝试将Bar包装到MSForms.Frame中,并且在需要重新绘制时,只需在此框架中调用它即可。在这种情况下,其余用户窗体及其控件不应受到影响,而仅应重新绘制框架。

Me.Frame1.Repaint ' Me is the main user form

  

而不是使用单独的进度条,因为这似乎是   在顶部还是在后台方面,都是不可靠的。

可以使用单独的 modal 形式轻松解决此问题,该表单将显示进度。此表单将具有取消按钮,并且在显示时将引发事件Start,因此调用表单可以开始执行长时间运行的工作,而在用户单击取消按钮以过早地取消进餐时,事件将开始事件Cancel。例如,HTH。

  

UserFormProgress

Option Explicit

Public Event Start()
Public Event Cancel(ByRef ignore As Boolean)

Private Sub CommandButtonCancel_Click()
    Dim ignoreCance As Boolean
    ignoreCance = False
    RaiseEvent Cancel(ignoreCance)
    If ignoreCance Then
        Exit Sub
    Else
        Unload Me
    End If
End Sub

Private Sub UserForm_Activate()
    Static isActivated As Boolean
    Me.Repaint
    If Not isActivated Then
        ' ensure only once activation
        isActivated = True
        RaiseEvent Start
        Unload Me
    End If
End Sub

Public Sub Update(ByVal newValue As Long)
    ' update progrress bar here
    ' Pseudo code: Me.Progress.Value = newValue etc.
    Me.Repaint
End Sub
  

UserFormMain

Option Explicit

Private WithEvents progress As UserFormProgress
Private cancelProgresForm As Boolean

Private Sub CommandButtonDoSomethingLongRunning_Click()
    Set progress = New UserFormProgress
    ' Set progress form
    ' progress.Caption = ...
    ' progress.MaxValue = 123456789
    progress.Show vbModal
End Sub

Private Sub progress_Start()
    ' Callback from progress form, here runs the lung running process
    ' calculate some complete status value
    Dim completeValue As Long
    completeValue = 0
    cancelProgresForm = False
    Do
        completeValue = completeValue + 1
        progress.Update completeValue
        DoEvents
    Loop While cancelProgresForm = False And completeValue < progres.MaxValue 
End Sub

Private Sub progress_Cancel(ignore As Boolean)
    If MsgBox("Do you want to cancel?", vbQuestion Or vbYesNo) = vbNo Then
        ignore = True
    Else
        ignore = False
        cancelProgresForm = True
    End If
End Sub