选择工作表的功能

时间:2015-10-16 00:36:50

标签: excel vba excel-vba

我正在尝试编写一个VBA函数来获取一个函数(“Rollup”)来在选择工作表时更新范围的值。

我在特定的工作表代码中针对不同的工作表重复了这一点,但关于如何创建单个函数,我将丢失带有范围名称的工作表名称(例如“rngXF”) )和汇总函数的值(例如“XF”)

Private Sub Worksheet_Activate()
Dim c As Range
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

For Each c In Range("rngXF")
    c.Value = Rollup(c, "XF")
Next c

Application.Calculation = xlCalculationAutomatic
Application.Calculate
Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

您可以将它放在任何希望RollUp工作的工作表模块中:

Private Sub Worksheet_Activate()
    Call Calculate_RollUp(Me, "rngXF", "XF")
End Sub

并将其置于常规模块中:

Public Sub Calculate_RollUp(SheetObject As Worksheet, Range_Name As String, RollUp_Argument As String)
Dim c As Range
With Application
    .EnableEvents = False
    .Calculation = xlCalculationManual
    .ScreenUpdating = False

    For Each c In SheetObject.Range(Range_Name)
        c.Value = Rollup(c, RollUp_Argument)
    Next c


    .Calculation = xlCalculationAutomatic
    .Calculate
    .EnableEvents = True
    .ScreenUpdating = True
End With
End Sub