如何汇总多个工作表中的值范围

时间:2018-07-18 13:15:35

标签: excel vba excel-vba sum

我想对120个工作表中的相同值范围(例如B3:B292)求和,使得:ΣB3,ΣB4,ΣB5......ΣB292。

下面的VBA代码没有收到错误,但也没有返回任何值。

 Sub FAggreg1PNFAWO()

 Dim Aggreg1PNFAWO As Workbook
 Dim WS_Count As Integer
 Dim filePath As String
 Dim i As Integer
 Dim TotalNp As Variant

 filePath = "Directory"

 Set Aggreg1PNFAWO = Workbooks.Open(filePath, ReadOnly:=True)
 WS_Count = Aggreg1PNFAWO.Worksheets.Count


For i = 1 To WS_Count
'Sheets(i).range("B3:B292") <> "" And
If IsNumeric(Sheets(i).range("B3:B292")) Then
    TotalNp = TotalNp + Sheets(i).range("B3:B292")
End If
Next
ActiveWorkbook.Close
ThisWorkbook.Activate
ActiveSheet.range("T4:T293").Value = TotalNp

End Sub

2 个答案:

答案 0 :(得分:0)

在这种情况下,请尝试以下操作:

Sub FAggreg1PNFAWO()
Dim Aggreg1PNFAWO As Workbook, myWB As Workbook
Dim WS_Count As Integer, i As Integer
Dim filePath As String
Dim TotalNp As Variant

Set myWB = ActiveWorkbook
filePath = "Directory"

Set Aggreg1PNFAWO = Workbooks.Open(filePath, ReadOnly:=True)
WS_Count = Aggreg1PNFAWO.Worksheets.Count

For X = 3 To 292
    For i = 1 To WS_Count
        If IsNumeric(Sheets(i).Range("B" & X)) Then
           TotalNp = TotalNp + Sheets(i).Range("B" & X).Value
        End If
    Next
    myWB.Activate
    myWB.ActiveSheet.Range("T" & i + 1).Value = TotalNp
    TotalNp = 0
    Aggreg1PNFAWO.Activate
Next X

End Sub

答案 1 :(得分:0)

您可以在此处使用SUM函数来执行此操作。在下面的答案中,假设B293单元为空并将其用于求和。如果该单元格中有一些数据,请选择其他空单元格,然后尝试执行此操作。

Sub Sum()

Dim Project1P As Workbook
    Dim WS_Count As Integer
    Dim i As Integer
    Dim V As Variant

    Set Project1P = Workbooks.Open("C:\Users\Nandan\Desktop\SO\SO1.xlsx")
    WS_Count = Project1P.Worksheets.Count
    sumrange (WS_Count)

End Sub

Function sumrange(TotalSheets As Integer)

     Dim reserves As Variant

     For i = 1 To TotalSheets
       Sheets(i).range("B" & 293).Formula = "=SUM(B3:B292)"
     Next

     For i = 1 To TotalSheets
      reserves = reserves + Sheets(i).range("B" & 293)
     Next

     For i = 1 To TotalSheets
      Sheets(i).range("B" & 293).Clear
     Next  

    MsgBox "Total of all sheets :" & reserves

End Function