【问题标题】:Sum all column values after each import每次导入后对所有列值求和
【发布时间】:2019-07-07 17:44:46
【问题描述】:

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

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

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

【问题讨论】:

  • 你可以对一整列求和,对吧?空白单元格不会影响总数。
  • 另外,删除括号:MsgBox manhours。然后检查,你可以做MsgBox manhours = sh.Range("31").Value
  • 是的,但是您是否知道一种仅对从工作表中添加的列中的值求和的方法?如果我总结了工作表 2 的总小时数,并且列中的工作表 1 已经有小时数。
  • 也许更重要的是,您永远不会在循环中更新 erow。所以你不断地覆盖相同的单元格。
  • i 循环从哪里开始?我只看到Next i。试试declaring your variables close to where they are used。这将有助于防止未使用的变量,使其更易于阅读。

标签: excel vba


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多