如何在Excel中创建相互依赖的列?

时间:2015-11-20 21:40:03

标签: excel vba excel-vba

我想要创建的是预算电子表格,可以将值输入到每日,每周,每月或每年列的一个单元格中,并且它将在整行中计算其他列的内容。

          A                   B                  C                   D                  E
1  CATEGORY        DAILY BUDGET      WEEKLY BUDGET      MONTHLY BUDGET      YEARLY BUDGET
2  Restaurants            $1.43            *$10.00*             $43.45            $521.43
3  Fuel                   $3.29             $23.01            *$100.00*         $1,200.00
4  Daily coffee          *$1.65*            $11.55              $50.19            $602.25
5  Auto Insurance         $3.29             $23.01             $100.00         *$1,200.00*

如上所示,星号表示输入一阶值的位置。例如,在每周预算列中输入的$ 10会计算其他三个值中的值,依此类推其余行,这些行在每个不同的列中都会输入一阶值。

我知道它涉及一些Excel VBA。事实上,Yahoo Answers上的这个答案非常接近我想要做的事情,除非我需要它来处理活动单元格各自行的列。

编辑:添加了对我的表的列和行引用,这是我的代码我已经修改过:

Private Sub PeriodConversion(ByVal Target As Range)
Application.EnableEvents = False
If Target.Address = "$B$2" Then
    [C2] = [B2] * 7
    [E2] = [B2] * 365
    [D2] = [E2] / 12
ElseIf Target.Address = "$C$2" Then
    [B2] = [C2] / 7
    [E2] = [B2] * 365
    [D2] = [E2] / 12
ElseIf Target.Address = "$D$2" Then
    [E2] = [D2] * 12
    [B2] = [E2] / 365
    [C2] = [B2] * 7
ElseIf Target.Address = "$E$2" Then
    [D2] = [E2] / 12
    [B2] = [E2] / 365
    [C2] = [B2] * 7
End If
Application.EnableEvents = True
End Sub

虽然它似乎没有起作用..:\

1 个答案:

答案 0 :(得分:2)

我没有测试过这个,但根据你开始的想法,或许试试这个:

(将代码放在表格所在的工作表中)

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Row=1 then Exit Sub

    Application.EnableEvents = False
    Select Case Target.Column
        Case 2
            '    [C2] = [B2] * 7
            Target.Offset(0, 1).Value = Target.Value * 7
            '    [E2] = [B2] * 365
            Target.Offset(0, 3).Value = Target.Value * 365
            '    [D2] = [E2] / 12
            Target.Offset(0, 2).Value = Target.Offset(0, 3).Value / 12
        Case 3
            '    [B2] = [C2] / 7
            Target.Offset(0, -1).Value = Target.Value / 7
            '    [E2] = [B2] * 365
            Target.Offset(0, 2).Value = Target.Offset(0, -1).Value * 365
            '    [D2] = [E2] / 12
            Target.Offset(0, 1).Value = Target.Offset(0, 2).Value / 12
        Case 4
            '    [E2] = [D2] * 12
            Target.Offset(0, 1).Value = Target.Value * 12
            '    [B2] = [E2] / 365
            Target.Offset(0, -2).Value = Target.Offset(0, 1).Value / 365
            '    [C2] = [B2] * 7
            Target.Offset(0, -1).Value = Target.Offset(0, -2).Value * 7
        Case 5
            '    [D2] = [E2] / 12
            Target.Offset(0, -1).Value = Target.Value / 12
            '    [B2] = [E2] / 365
            Target.Offset(0, -3).Value = Target.Value / 365
            '    [C2] = [B2] * 7
            Target.Offset(0, -2).Value = Target.Offset(0, -3).Value * 7
    End Select
    Application.EnableEvents = True

End Sub