1

我正在尝试使用 DateAdd 函数将一个月添加到日期,格式为 2018 年 11 月 30 日,但无论输入什么日期,输出都是 12:00:00AM

oneCell 和 twoCell 的范围都是 Excel 工作表中的日期格式

 For Each aWorksheet In ActiveWorkbook.Worksheets
    If Left(aWorksheet.Name, 1) = "#" Then
        siteNum = Trim(Right(Left(aWorksheet.Name, 5), 4))

        Set oneCell = aWorksheet.Range("C:C").Find("2018")
        Set twoCell = aWorksheet.Range("D:D").Find("2018")

        If oneCell.Row > twoCell.Row Then
            Set oneCell = oneCell.Offset(-1, 0)
        End If

        Do While oneCell.Value <> ""

            billMonthDate = GetBillMonth(oneCell.Value, twoCell.Value)

然后调用的函数:

Public Function GetBillMonth(ByVal startDate As Date, ByVal endDate As Date) As Date
Dim billMonth As Date
Dim startMonthDays As Integer
Dim endMonthDays As Integer

If DateDiff("m", startDate, endDate) > 1 Then
    billMonth = DateTime.DateAdd("m", 1, startDate)

Else
    startMonthDays = DateDiff("d", startDate, DateSerial(Year(startDate), Month(startDate) + 1, -1))
    endMonthDays = Day(endDate)

    If startMonthDays > endMonthDays Then
        billMonth = oneCellDate
    ElseIf startMonthDays < endMonthDays Then
        billMonth = endDate
    Else
        'fuck me
    End If
End If

GetBillMonth = billMonth

End Function

编辑:开始日期来自我正在分析的电子表格。宏循环并查看很多日期,所以我不能只是将日期连续输入来解决这个问题。我只需要 dateadd 工作

4

2 回答 2

0

这是任何有兴趣的人的解决方法:

    If Month(startDate) + 1 > 12 Then
        billMonth = DateSerial(Year(startDate) + 1, 1, 1)
    Else
        billMonth = DateSerial(Year(startDate), Month(startDate) + 1, 1)
    End If
于 2019-03-26T14:48:36.943 回答
0

始终使用真实的日期值,不要使用看起来像日期的字符串。

Sub AddOneMonth()  
    Dim StartDate As Date
    StartDate = DateSerial(2018, 11, 30)

    Dim BillMonth As Date
    BillMonth = DateAdd("m", 1, StartDate)

    Debug.Print BillMonth   '2018-12-30  
End Sub

如果使用细胞……</p>

Sub AddOneMonth()  
    Dim StartDate As Date
    StartDate = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value

    Dim BillMonth As Date
    BillMonth = DateAdd("m", 1, StartDate)

    ThisWorkbook.Worksheets("Sheet1").Range("A2").Value = BillMonth
    ThisWorkbook.Worksheets("Sheet1").Range("A2").NumberFormat = "MM/dd/yyyy"
End Sub
于 2019-03-25T15:02:47.930 回答