VBA 用户窗体应该使用哪种显示模式来显示数据、控制它并确认它是正确的?

Which display mode should one use for a VBA UserForm in order to display data, controll it and confirm it is ok?

我计划了以下程序:

1.用户使用用户表单选择数据

2。用户使用通常的评论数据 Excel

3。用户确认数据正常(例如使用用户表单)

4。数据已保存

全部在同一个 VBA 程序中。

这是我的原型:

模块:

Sub ControlDataUI()
Dim Ui As New UserForm1
Dim Confirmend as Boolean
Debug.Print "dostuff"

With Ui
    .Show (False) 'or .Show(True)
    While Not .IsHiden
    Wend
    Confirmed=.Confirmed
End With

Debug.Print "Do some more stuff!"

If Confirmed then Call SaveStuff 

Debug.Print "I will die!!"
End Sub

Userform1:

Private Type TView
    IsCancelled As Boolean
    Confirmed As Boolean
    IsHiden As Boolean
End Type

Private this As TView

Public Property Get Confirmed() As Boolean
    Confirmed = this.Confirmed
End Property
Public Property Get IsHiden() As Boolean
    IsHiden = this.IsHiden
End Property

Private Sub CommandButton1_Click()
Debug.Print "YES!!!!"
this.Confirmed = True
this.IsHiden = True
Me.Hide
End Sub

Private Sub CommandButton2_Click()
Debug.Print "NO?!?!"
this.Confirmed = False
this.IsHiden = True
Me.Hide
End Sub

Private Sub UserForm_Terminate()
Debug.Print "Murder! I was killed!"
End Sub

现在问题:

无模型

当使用无模式时,会显示用户表单,但代码会保持 运行 直到完成。我试图通过 While Not .IsHiden 结构停止代码从 运行 开始。代码冻结 Excel 因为它是一个无限循环。所以排除了。 有没有办法用无模式显示来实现这个?

模态

如果我使用模态显示,excel 的使用将被阻止并且仅显示用户表单。

结论:模态和无模显示都不能使用户控制sheet中的数据。这个问题有解决办法吗?

我明白了!

问题的解决方法如下:DoEvents

模块

Sub ControlDataUI()
Dim Ui As New UserForm1
Dim IsConfirmed As Boolean

Debug.Print "dostuff"

Application.ScreenUpdating=True
With Ui
    .Show (0)
    While Not .IsHiden
        DoEvents
    Wend
    If .IsCancelled Then Exit Sub
    IsConfirmed = .Confirmed
End With

Debug.Print "Do some more stuff!"

If IsConfirmed Then
    Debug.Print "SaveStuff"
End If

Debug.Print "I will die!!"
End Sub

用户窗体

Private Type TView
    IsCancelled As Boolean
    Confirmed As Boolean
    IsHiden As Boolean
End Type

Private this As TView
Public Property Get IsCancelled() As Boolean
    IsCancelled = this.IsCancelled
End Property
Public Property Get Confirmed() As Boolean
    Confirmed = this.Confirmed
End Property
Public Property Get IsHiden() As Boolean
    IsHiden = this.IsHiden
End Property

Private Sub CommandButton1_Click()
Debug.Print "YES!!!!"
this.Confirmed = True
this.IsHiden = True
Me.Hide
End Sub

Private Sub CommandButton2_Click()
Debug.Print "NO?!?!"
this.Confirmed = False
this.IsHiden = True
Me.Hide
End Sub

Private Sub UserForm_Click()

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
this.IsCancelled = True
Me.Hide
End Sub

Private Sub UserForm_Terminate()
Debug.Print "Murder! I was killed!"
End Sub

所以这个想法是正确的,但是 while 循环必须包含一个 DoEvents 以便处理来自用户的事件。

总结:

1.无模式用户表单

2。 While 循环 DoEvents 直到用户确认

这允许用户随时控制 sheet 和确认。用户确认数据正常后,代码会运行

感谢@Tom 和@Zac