如何在Excel中单击特定单元格时弹出日历,并在该单元格中插入日期和时间?

时间:2017-10-18 12:53:17

标签: excel excel-vba vba

我使用以下代码选择一个单元格并使用日期选择器弹出窗口。它工作正常。但是,对于我的应用程序,我需要用户输入日期和时间(上午/下午)。如何在日期旁边添加时间?当我格式化单元格以显示日期和时间时,时间默认为12:00 AM。请指教。

用户窗体

    Private Sub MonthView1_DateClick(ByVal DateClicked As Date)
 On Error Resume Next
   Dim xRg As Object
   For Each xRg In Selection.Cells
      xRg.Value = DateClicked
   Next xRg
   Unload Me
End Sub

Sheet 1中

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("M4:M300")) Is Nothing Then UserForm3.Show
End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

假设评论中的问题是正确的,您可以执行以下任一操作...在userform(两种方式中的一种)中:

1

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("M4:M300")) Is Nothing Then UserForm3.Show
    UserForm3.TextBox1.Value = Format(Time, "hh:mm AM/PM") 'Assumes you have a textbox in the Userform
End Sub

2

Private Sub UserForm3_Initialize()
    TextBox1.Value = Format(Time, "hh:mm AM/PM")
End Sub

来自selectionchange:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("M4:M300")) Is Nothing Then UserForm3.Show
    ActiveCell.Formula = Format(Time, "hh:mm AM/PM") 'Activecell as the current range
End Sub

如果您只想在Excel中使用某些顺序,则可能需要if语句,如:

If ActiveCell.Offset(-1,0).Value="" Then Exit Sub