【发布时间】: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。这将有助于防止未使用的变量,使其更易于阅读。