每次导入后对所有列值求和

时间:2019-07-07 17:44:46

标签: excel vba

我当前的代码从不同的工作簿中读取工时(整数值)并将其导出到主输出工作表中的一列。每次导入后,我想对导出到主工作表的总小时数求和,但是, 我不确定如何在不汇总整个专栏的情况下这样做。此外,在汇总每张纸上的总工时后,我想将此值与纸上的值进行比较,以确认是否正确复制了所有行。

每次导入后,我的输出表如下:

data----------data----------hours(sheet1)    
data----------data----------hours(sheet1)    
data----------data----------hours(sheet1)    
data----------data----------hours(sheet2)    
data----------data----------hours(sheet2)

我当前的代码如下:

Option Explicit

Sub manhours()
    Dim Files As Variant
    Dim i As Long
    Dim j As Long
    Dim sh As worksheet
    Dim outputsheet As Worksheet
    Dim erow As long
    Dim manhours As Long

    Workbooks.Open Files(i)
    Set sh = Sheets("manhours")

    For j = 2 to 30   
        erow = outputsheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 'empty row
        If IsEmpty(Cells(j, 3) = False Then
            outputsheet.Cells(erow, 1).Resize(1, 2).Value = sh.Cells(j, 1).Resize(1, 2).Value 'copies the first 2 columns containing other data values
            outputsheet.Cells(erow, 3) = sh.Cells(j, 3) 'column 3 from sh contains manhours
        End If
    Next j

    manhours = Application.WorksheetFunction.Sum(outputsheet.Columns(3)) 'unsure how to sum only the values from sheet i and not the entire column
    MsgBox (manhours) ' msgbox than gives the total man hours

    manhours = sh.Range("C31") 'total manhours from sheet is in sh.Range("C31")
    'MsgBox (True/False) 'unsure how to do this

    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

我认为这里不需要使用WorksheetFunction.Sum

一个选择:保持一个连续的总和,就像这样:

manhours = 0 ' reset manhours to 0 for each new file

For j = 2 to 30
    If Not IsEmpty(sh.Cells(j, 3).Value) Then 
        ...
        outputsheet.Cells(erow, 3).Value = sh.Cells(j, 3).Value
        manhours = manhours + sh.Cells(j, 3).Value ' could add an IsNumeric check here to avoid a Type Mismatch
    End If
Next j

MsgBox manhours ' no parentheses
MsgBox manhours = sh.Range("C31").Value