计算的自动修改

我创build了一个代码,它允许我将来自不同工作表中不同单元格的(统一)数字汇总到一张工作表(合并工作表中包含总计 – 称为工作表0)

然后我创build了一个button来激活这些代码,它的工作原理。

我想要知道的是:每当我在任何一个单元格中修改一个数字时,它都会直接修改我的最终结果(在sheet0上),而不必在button上按下另一个时间。

这是与我的button关联的代码:

Sub Consolidate() Application.Calculation = xlCalculationAutomatic 'I thought this line would help me Dim Sheet As Worksheet Dim Consolidated As Long For y = 2 To 152 For x = 2 To 14 Consolidated = 0 For Each Sheet In Sheets If Right(Sheet.Name, 5) = "E2016" Then If IsNumeric(Sheet.Cells(y, x).Value) Then Consolidated = Consolidated + CLng(Sheet.Cells(y, x).Value) Sheet0.Cells(y, x) = Consolidated End If If Not IsNumeric(Sheet.Cells(y, x).Value) Then Sheet0.Cells(y, x) = " " End If If IsEmpty(Sheet.Cells(y, x).Value) Then Sheet0.Cells(y, x) = " " End If End If Next Next Next End Sub 

正如在注释中提出的,每次Change Event任何表单时,都可以使用“ Change Event来运行代码。 但是,这可能会减慢你的Excel,因为 – 每次更改后 – 你的代码将不得不运行。

所以,我build议宁可在condolidated Worksheet_Activate上使用事件Worksheet_Activate 。 这样,每次您打开Sheet0来查看统一数字时,您的代码就会运行。

为了实现这一点,进入VBE并双击Sheet0来查看该表的代码。 然后插入下面的代码:

 Private Sub Worksheet_Activate() Call Consolidate End Sub 

根据你的评论,似乎你的问题/目标已经改变。 为了在Sheet0上得到这个dynamic公式,你可能想要尝试下面的代码(没有保证,因为我不能在没有实际工作表的情况下testing它):

 If IsNumeric(Sheet.Cells(y, x).Value2) Then If Len(Sheet0.Cells(y, x).Formula) = 0 Then Sheet0.Cells(y, x).Formula = "=SUM('" & Sheet.Name & "'!" & Sheet.Cells(y, x).Address & ")" Else Sheet0.Cells(y, x).Formula = Left(Sheet0.Cells(y, x).Formula, Len(Sheet0.Cells(y, x).Formula) - 1) & ",'" & Sheet.Name & "'!" & Sheet.Cells(y, x).Address & ")" End If End If 

由于我没有你的工作表,我无法testing它。 希望它按原样工作。 如果没有,至less你明白了。

如果我正确地理解了你,你可以在SUM里面使用一个3:

= SUM(Sheet2:Sheet8!A1)或= SUM(Sheet2:Sheet8!A1:Z99)

那么我真的很愚蠢,但我有一个问题:这是我的公式(积分拉尔夫,上)正在为我所有的细胞,而不是第一个B:2。 在这一个没有价值的,它的公式,这是显示在这种forms:'阿联酋E2016'!$ B $ 2,'KSA E2016'!$ B $ 2,'塞浦路斯E2016'!$ B $ 2,'卡塔尔E2016' !$ B $ 2)

在其他细胞中,这里是公式:= SUM('LEB E2016'!$ B $ 4,'UAE E2016'!$ B $ 4,'KSA E2016'!$ B $ 4,'CYPRUS E2016'!$ B $ 4,'QATAR E2016 '!$ B $ 4),但是如果我不点击单元格,则会显示该值。 这是我所需要的,它在任何地方工作,但不在我的第一个牢房里。

这让我疯狂。 我试图解决它与断点,但没有做我不明白。 对不起,所有这些问题,但我开始在我自己的2个星期的VBA,我真的不掌握它呢! 这里是公式:

  Sub Consolidate() Dim Sheet As Worksheet 'Dim Consolidated As String For y = 2 To 152 For x = 2 To 14 'Consolidated = "" For Each Sheet In Sheets If Right(Sheet.Name, 5) = "E2016" Then If IsNumeric(Sheet.Cells(y, x).Value) Then 'Consolidated = Consolidated + "+" + Sheet.Cells(y, x).Formula 'Sheet0.Cells(y, x) = Consolidated If Len(Sheet0.Cells(y, x).Formula) = 0 Then Sheet0.Cells(y, x).Formula = "=SUM('" & Sheet.Name & "'!" & Sheet.Cells(y, x).Address & ")" Else Sheet0.Cells(y, x).Formula = Left(Sheet0.Cells(y, x).Formula, Len(Sheet0.Cells(y, x).Formula) - 1) & ",'" & Sheet.Name & "'!" & Sheet.Cells(y, x).Address & ")" End If End If If Not IsNumeric(Sheet.Cells(y, x).Value) Then Sheet0.Cells(y, x) = " " End If If IsEmpty(Sheet.Cells(y, x).Value) Then Sheet0.Cells(y, x) = " " End If End If Next Next Next End Sub