Excel VBA / Formula,用于根据其他2个单元格的值填充3个特定单元格

时间:2014-07-02 10:49:11

标签: excel vba excel-vba excel-formula

在工作簿中,我的报告设置如下:

         A              B            C            D            E
1 Reporting Year        2012
2 Reporting Quarter     Q3
3                                 Jul-12        Aug-12       Sep-12
4
5

我正在尝试根据B1和B2中选择的内容自动化单元格C3,D3和E3的数量。例如,如果B1 = 2012,B2 = Q3,我希望单元格C3,D3和E3以表格中显示的格式填充该季度的月份。例如C3 = 7月12日,D3 = 8月12日,E3 = 9月12日

提前致谢!我试图通过命名范围做一些事情,但它变得非常笨拙,我确信有一种更简单的方法!

3 个答案:

答案 0 :(得分:1)

使用三个简单的公式很容易做到:

C3: =DATE(B1, (VALUE(RIGHT(B2, 1)) - 1) * 3 + 1, 1)
D3: =DATE(B1, (VALUE(RIGHT(B2, 1)) - 1) * 3 + 2, 1)
E3: =DATE(B1, (VALUE(RIGHT(B2, 1)) - 1) * 3 + 3, 1)

然后适当地格式化日期或使用TEXT(C3, "MMM-YY")功能。

替代:

C3: =DATE(B1, VALUE(RIGHT(B2, 1)) * 3 - 2, 1)
D3: =DATE(B1, VALUE(RIGHT(B2, 1)) * 3 - 1, 1)
E3: =DATE(B1, VALUE(RIGHT(B2, 1)) * 3 - 0, 1)

答案 1 :(得分:1)

一个(很多!)替代品:

=DATE($B1,SUBSTITUTE($B2,"Q",)*3+COLUMN()-5,1)  
在C3中

并复制到E3,格式化为适合。

可以简化B2格式"Q"#

答案 2 :(得分:0)

在您的VBA表模块中

添加以下内容:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim IntersectRng As Range
Dim Year As String, Quarter As String
Dim monthStart As Integer
Dim Months() As Variant

Set IntersectRng = Application.Intersect(Target, Range("B1:B2"))
Months = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

If (Not IntersectRng Is Nothing) Then

    Year = Range("B1")
    Quarter = Range("B2")

    Select Case Quarter

        Case "Q1"
            monthStart = 0
        Case "Q2"
            monthStart = 3
        Case "Q3"
            monthStart = 6
        Case "Q4"
            monthStart = 9
        Case Else

    End Select

    Range("C3").Value = Months(monthStart) & "-" & Year
    Range("D3").Value = Months(monthStart + 1) & "-" & Year
    Range("E3").Value = Months(monthStart + 2) & "-" & Year

End If