VBA为日期添加mmm-yy和Business Quarter

时间:2017-03-24 05:02:50

标签: excel vba excel-vba

我创建了一个VBA,以便在选择下拉列表时自动填充日期,但需要格式化为mmm-yy的日期和业务季度将填入下一个单元格。

以下是我创建的内容,请协助添加mmm-yy和Business Quarter。

With Target
    If .Column <> 10 Or .Row < 1 Then Exit Sub
    If .Value = "Select" Then
        If .Offset(0, 1).Value = "" Then
            .Offset(0, 1).NumberFormat = "mm/dd/yy"
            .Offset(0, 1).Value = Now - 1      
        End If

1 个答案:

答案 0 :(得分:1)

获得业务季度有点主观。财政年度在地区之间变化。以下示例假设Jan-Mar = Q1,Apr-Jun = Q2等:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    With Target
        If .Column <> 10 Or .Row < 1 Then Exit Sub
        If .Value = "Select" Then
            If .Offset(0, 1).Value = "" Then
                .Offset(0, 1).NumberFormat = "mm/dd/yy"
                .Offset(0, 1).Value = Now - 1
                .Offset(0, 2).Value = Now - 1
                .Offset(0, 2).NumberFormat = "mmm-yy" '<~~ mmm-yy
                .Offset(0, 3).Value = GetBusinessQuarter(.Offset(0, 1)) '<~~ business quarter
            End If
        End If
    End With

End Sub

Function GetBusinessQuarter(dt As Date) As String

    ' credit: https://exceljet.net/formula/get-fiscal-quarter-from-date
    GetBusinessQuarter = "Q" & CStr(Choose(Month(dt), 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4))

End Function