Excel VBA:使用 DatePicker 在单元格中获取正确的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24741849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:50:42  来源:igfitidea点击:

Excel VBA: Get the right date into a cell using DatePicker

excelvbaexcel-vba

提问by Nuno Nogueira

I have a UserForm with a DatePicker control in it. It works fine, except when copying the selected date to the spreadsheet. This is the code:

我有一个带有 DatePicker 控件的用户窗体。它工作正常,除非将所选日期复制到电子表格。这是代码:

Range("A1").Value = UserForm1.DTPicker1.Value

Which returns:

返回:

00:00:00

In cell A1, no matter what date has been selected.

在单元格 A1 中,无论选择了什么日期。

回答by hnk

You cell formatting might be set to Time instead of Date.

您的单元格格式可能设置为时间而不是日期。

Try changing that to see if it works.

尝试更改它以查看它是否有效。

Also, make formatting 'General' AFTER this step, to see if anything has been pasted in "A1".

此外,在此步骤后格式化“常规”,以查看是否在“A1”中粘贴了任何内容。

回答by rae

You should need an intermediate variable to get it, like below:

您应该需要一个中间变量来获取它,如下所示:

t = Me.DTPicker1.Value
ws.Range("A1") = t

回答by John O'Brien

Make sure that the command to transfer the data is located in the same form or page of a multipage form as the DTPicker itself.

确保传输数据的命令位于与 DTPicker 本身相同的表单或多页表单的页面中。

For some reason it wont work when the two are separated and will display a zero in the target cell. That zero is the "time" part of the date which has been switched off. Although the "Date" part refuses to transfer over, for some reason the time does, and so that zero time is read in the cell as time zero which is mid-day.

出于某种原因,当两者分开时它不会工作,并且会在目标单元格中​​显示零。该零是已关闭的日期的“时间”部分。尽管“日期”部分拒绝转移,但由于某种原因时间会转移,因此在单元格中读取零时间作为时间零,即正午。

So in summary:

所以总结一下:

Keep the DTPicker and transfer control on the same page and that should solve the problem.

将 DTPicker 和转移控制保持在同一页面上,这应该可以解决问题。

The code is pretty simple. It's

代码非常简单。它是

Sheet1.Range("AA9") = Me.DTPicker1.Value