为同一工作表中的多个日期选择器重用UserForm VBA代码

时间:2015-12-16 17:47:29

标签: excel vba excel-vba calendar

我想知道如何重用我所拥有的VBA代码在同一工作表上创建多个日历日期选择器,这些工作表将输入到不同的单元格。我已经尝试更改.frm文件的名称并重新导入它只是更改单元格引用输出,但Excel每次都拒绝它并说该名称已被使用。我正密切关注this example

如果您知道如何隐藏可点击图片的代码,直到选择了带有日期的单元格,

加分。

以下是我目前在frmCalendar中使用的代码:

Private Sub cmdClose_Click()
    Unload Me
End Sub

Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
   On Error Resume Next
   Dim cell As Object
   For Each cell In Range("C18")
      cell.Value = DateClicked
   Next cell
   Unload Me
End Sub

Private Sub UserForm_Initialize()
   If IsDate(ActiveCell.Value) Then
      Me.MonthView1.Value = Range("C18")
   End If
End Sub

...和我的Module1代码:

Sub Sample()
    frmCalendar.Show
End Sub

基本上,我有一个日历可以卸载到C18中。但是,我希望在我的工作表中最多有10个日历按钮,它们具有不同的输出单元格,因此它们都可以具有不同的日期。

以下是日历按钮输出到C18的示例。它已被分配宏“样本”

enter image description here

那么如何在多个日历按钮中重复使用我的代码呢? 如果有代码隐藏日历按钮,直到选中该单元格,就会获得奖励。

1 个答案:

答案 0 :(得分:1)

您可以在表单打开时存储选定的单元格,并在关闭表单时使用该单元格。

Dim cell As Range 'selected cell when launched

Private Sub cmdClose_Click()
    Unload Me
End Sub

Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
   On Error Resume Next
   cell.Value = DateClicked
   Unload Me
End Sub

Private Sub UserForm_Initialize()
   Set cell = Selection.Cells(1)
   If IsDate(cell.Value) Then
      Me.MonthView1.Value = cell.Value
   End If
End Sub