vba 从VBA中的日期中减去?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6986940/
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
Subtracting from a date in VBA?
提问by Andrei Ion
I'm having big problems doing operation with the date in Excel VBA. I have a form that has a textbox where the user will enter the date. The problem is that he may enter it in different formats (eg, 1.08.2011 for 1st of August, or 8/1/11 for the same day). Now what I want to do is to subtract some days from that date that he enters in the TextBox. I had to success so far and I don't know how to do it. I tried something like this
我在 Excel VBA 中对日期进行操作时遇到了大问题。我有一个表单,它有一个文本框,用户将在其中输入日期。问题是他可能以不同的格式输入它(例如,8 月 1 日的 1.08.2011,或同一天的 8/1/11)。现在我想要做的是从他在 TextBox 中输入的日期减去几天。到目前为止,我必须成功,但我不知道该怎么做。我试过这样的事情
Format((Format(Me.datalivrare.Value, "dd.mm.yyy") - 4), "dd.mm.yyyy")
Where datalivrare is that textbox where the user enters the date and 4 is the number of days I want to subtract from that date... and I want the format to always be dd.mm.yyyy no matter what they enter in that textbox.
其中 datalivrare 是用户输入日期的文本框,4 是我想从该日期中减去的天数……我希望格式始终为 dd.mm.yyyy,无论他们在该文本框中输入什么。
回答by Taryn
I suggest looking at the DateAdd function for VBA
我建议查看 VBA 的 DateAdd 函数
http://www.techonthenet.com/excel/formulas/dateadd.php
http://www.techonthenet.com/excel/formulas/dateadd.php
http://office.microsoft.com/en-us/access-help/dateadd-function-HA001228810.aspx
http://office.microsoft.com/en-us/access-help/dateadd-function-HA001228810.aspx
You could do the following:
您可以执行以下操作:
Format(DateAdd("d", -4, CDate(Me.datalivrare.Value)), "dd.mm.yyyy")
回答by Einacio
回答by Lance Roberts
First cast to Date, then subtract days, then format appropriately:
首先转换为日期,然后减去天数,然后适当地格式化:
Format(DateAdd("d", -4, CDate(Me.datalivrare.Value)), "dd.mm.yyyy")
回答by CoveGeek
It is important to check if the user entered a value that VBA can interprit as a date so first you should:
检查用户是否输入了 VBA 可以解释为日期的值很重要,因此首先您应该:
If isDate(Me.datalivrare.Value) Then
str_Date = Format(DateAdd("d", -4, CDate(Me.datalivrare.Value)), "dd.mm.yyyy")
Else
MsgBox "Not a valid date value", vbCritical + vbOkOnly, "Invalid Entry"
End If
I think bluefeet's answer had the most information so far and I borrowed the use of DateAdd and CDate.
我认为 bluefeet 的答案到目前为止有最多的信息,我借用了 DateAdd 和 CDate 的用法。