VBA格式日期为上个月

时间:2017-09-22 07:55:22

标签: excel vba date

我在VBA相当新,这似乎是一件容易的事。我只是想让当前的日期用当前月代替前一个月和一天的常数为21,所以结果必须是yyyy - (m-1) - 21

到目前为止,我有一些想法,他们部分工作

Sub Test_Date()
     Dim x As String
     Dim p As String
   p = Format(Date, "mm") - 1
   x = Format(Date, "yyyy-" p "-21")
End Sub

如果我将MsgBx“p”恢复为我想要的但是,我不知道将它们连接成一个字符串的正确语法

Sub Test_Date()
   Dim x As String
     x = Format(Date, "yyyy-(Format(Date, "mm") - 1)-21")
End Sub

4 个答案:

答案 0 :(得分:1)

你也可以试试这个:

Function LastMonth() As Date
    Dim d As Date
        d = DateAdd("m", -1, Date)
    LastMonth = DateSerial(Year(d), Month(d), 21)
End Function

修改

根据需要格式化返回的日期:

Sub Test()
    MsgBox Format(LastMonth, "yyyy-mm-dd")
End Sub

答案 1 :(得分:0)

您可以使用DateSerial

这会接受年,月,日作为输入,并根据该日期推出日期。

因此,DateSerial(2017,9,22)将提供今天的日期 为了获得上个月的第21个你使用

DateSerial(Year(Date), Month(Date) - 1, 21) 

Year(Date)返回2017,Month(Date)返回9.

答案 2 :(得分:0)

使用dateadd函数(https://www.techonthenet.com/excel/formulas/dateadd.php):

DateAdd( interval, number, date )

or

DateAdd("m", 5, "22/11/2003")

答案 3 :(得分:0)

尝试

$tableData = '';

foreach ($events as $event) { 
    $tableData .= '<tr>';

    foreach ($event as $cell) {
        $tableData .= "<td>{$cell}</td>";
    }

    $tableData .= '</tr>';
}

$mail->Body = <<<MSG
        <html>
            <head>
                <title>Statistics</title>
            </head>
            <body>
                The start was: {$start} </br></br>
                The end was: {$end} </br></br>

                <table>{$tableData}</table>
            </body>
        </html>
MSG;