简体   繁体   English

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

[英]Reuse UserForm VBA Code for Multiple Date Pickers in Same Worksheet

I'm wondering how to reuse the VBA code that I have to create multiple Calendar date pickers on the same worksheet that will input to different cells. 我想知道如何重用我必须在将输入到不同单元格的同一工作表上创建多个日历日期选择器的VBA代码。 I have tried changing the name of the .frm file and re-importing it to simply change the cell reference output, but Excel rejects this every time and says the name is already in use. 我尝试更改.frm文件的名称并重新导入以仅更改单元格引用输出,但是Excel每次都拒绝此操作,并说该名称已被使用。 I'm closely following this example . 我正在密切关注这个例子

Bonus points if you know code for how to hide the clickable image until the cell with the date is selected. 如果您知道如何隐藏可单击图像直到选择带有日期的单元格的代码,则可以加分。

Here is the code that I am working with so far in frmCalendar: 这是到目前为止我在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

...and my code for Module1: ...以及我对Module1的代码:

Sub Sample()
    frmCalendar.Show
End Sub

So basically, I have one calendar that unloads into C18. 所以基本上,我有一个日历可以加载到C18中。 However, I would like to have up to 10 calendar buttons in my worksheet that have different output cells so they can all have different dates. 但是,我希望工作表中最多有10个日历按钮,它们具有不同的输出单元格,因此它们都可以具有不同的日期。

Here is an example where the calendar button outputs to C18. 这是一个日历按钮输出到C18的示例。 It has been assigned the Macro "Sample" 已为其分配了宏“样品”

在此处输入图片说明

So how can I reuse my code for multiple calendar buttons? 那么如何将我的代码重用于多个日历按钮? Bonus if there is code to hide the calendar buttons until the cell is selected. 如果有代码可以隐藏日历按钮,直到选中该单元格,则奖励。

You can store the selected cell when the form opens and use that when you close it. 您可以在窗体打开时存储选定的单元格,并在关闭时使用它。

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

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

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