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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:45:07  来源:igfitidea点击:

Subtracting from a date in VBA?

excelvba

提问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

the best to add and substract from dates on vba is dateadd()(with negative number for substractions) also, in your example code there's a missing y on the format string (it accepts 1, 2 or 4 y, only)

在 vba 上添加和减去日期的最佳方法是dateadd()(减法为负数),在您的示例代码中,格式字符串中缺少 y(仅接受 1、2 或 4 y)

回答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 的用法。