Macro to sum values from another Workbook with Multiple Sheets

不问归期 提交于 2019-12-11 15:14:58

问题


I am working on a project that requires me to sum multiple values in another excel workbook.

The other Workbook contains, say, 120 sheets. I want to take a certain value from each sheet, and sum it along with the rest. The cell reference for all the 120 values is fixed, for example J3.

Another thing worth mentioning (maybe) is that the sheet code names aren't organized (i.e. Sheet 1 all the way to Sheet 120), there have been several sheets added/removed in between.

Right now I'm getting

Run Time Error 424 Object Required

Sub SumProject1P()
    Dim Project1P As Workbook
    Dim reserves
    Dim WS_Count As Integer
    Dim i As Integer
    Dim V As Variant

    Set Project1P = Workbooks.Open("FILE PATH")
    WS_Count = Workbook.Worksheets.Count
    V = Workbook.Worksheets
    reserves = sumrange(Workbook.Worksheets(V).range(Cells(1, 8)))
End Sub


Function sumrange(range)
    summ = 0
    For i = 1 To WS_Count
        summ = summ + reserves
    Next
    reserves = summ
End Function

I hope to receive feedback and input.


回答1:


Here you go

Sub SumProject1P()

Dim Project1P As Workbook
Dim reserves As Long
Dim WS_Count As Integer
Dim filePath As String

    filePath = "Enter you file path"

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


   For i = 1 To WS_Count
    If Sheets(i).range("J3") <> "" And IsNumeric(Sheets(i).range("J3")) Then
        reserves = reserves + Sheets(i).range("J3")
    End If
   Next

   MsgBox "Total of all sheets :" & reserves
End Sub



回答2:


You are getting the object required error because you are not using the Worsheets.count function to any object.

Your code:

Set Project1P = Workbooks.Open("FILE PATH")
    WS_Count = Workbook.Worksheets.Count

You need to use this function for Project1P object.

 Set Project1P = Workbooks.Open("FILE PATH")
    WS_Count = Project1P .Worksheets.Count 

Santosh already gave you the simplest way. Still if you want to do it by using Function then try the below.

Sub Sum()

Dim Project1P As Workbook
    Dim WS_Count As Integer
    Dim i As Integer
    Dim V As Variant
    Set Project1P = Workbooks.Open("File path")
    WS_Count = Project1P.Worksheets.Count
    sumrange (WS_Count)

End Sub

Function sumrange(TotalSheets As Integer)

     Dim reserves As Integer

     For i = 1 To TotalSheets
         If Sheets(i).range("J3") <> "" And IsNumeric(Sheets(i).range("J3")) Then
             reserves = reserves + Sheets(i).range("J3")
        End If
     Next

    MsgBox "Total of all sheets :" & reserves

End Function


来源:https://stackoverflow.com/questions/51379712/macro-to-sum-values-from-another-workbook-with-multiple-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!