首页 > 解决方案 > 用户窗体中的月视图 - 自动关闭

问题描述

我想单击某个单元格并显示带有月视图的用户窗体,然后一旦我选择了一个日期并将其插入到单元格中,我希望用户窗体自动关闭

此代码在工作表中

Private Sub worksheet_selectionchange(ByVal target As Range)

    If Not Application.Intersect(Range("l14"), target) Is Nothing Then
        UserForm1.Show
    End If
End Sub

此代码位于用户窗体 - MonthView1

Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
    ActiveCell.Value = DateClicked
End Sub

任何帮助将不胜感激

标签: excelvbauserform

解决方案


UserForm1.Show有毒;您本质上是将状态存储在全局范围内,这将不可避免地导致问题。改为创建表单的新实例

If Not Application.Intersect(Range("l14"), target) Is Nothing Then
    With New UserForm1
        .Show
    End With
End If

现在,存在一个表单/对话框来收集用户输入,而不是使用该输入并更改单元格值。该输入会发生什么应该取决于使用该表单的代码,而不是取决于表单本身。使用属性公开所选Date值。

用户可以做两件事:要么他们选择一个日期并且你有一个SelectedDate,要么他们点击那个 [X] 按钮并关闭表单:你需要能够告诉用户做了什么。处理QueryClose它,并公开一个IsCancelled属性。

选择一个日期,或取消,应该隐藏表格,而不是破坏它。

Option Explicit
Private selectedValue As Date
Private cancelled As Boolean

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelled
End Property

Public Property Get SelectedDate() As Date
    SelectedDate = selectedValue
End Property

Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
    selectedValue = DateClicked
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = True
        cancelled = True
        Me.Hide
    End If
End Sub

现在您有了一个日期选择器表单,您可以在需要时重复使用它,因为它不知道也不关心所选值会发生什么:

If Not Application.Intersect(Range("l14"), target) Is Nothing Then
    With New UserForm1 ' todo: rename form to "DatePickerDialog" or something
        .Show
        If Not .IsCancelled Then
            target.Value = .SelectedDate
        End If
    End With
End If

推荐阅读