所以我有一年中每个月的数据,每个月分成两个15天的工作表。
我试图将两个工作表相加,然后将值放入编译工作表,然后继续下个月。
目前它只是从1月份开始添加所有内容,我尝试将其重置为0,但这只会导致所有内容都为零。
我可以很容易地在代码末尾应用一个公式来应用前一个单元格的减法,但我认为最好学习如何在VBA中执行此操作。也许我只是没有在谷歌中使用正确的词语。
感谢您的帮助。
Sub Sum()
Dim DestSh As Worksheet
Dim Sh As Worksheet
Dim lastcol As Long
Dim lastrow As Long
Dim destrow As Long
Dim prevval As Double
Dim nextval As Double
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Application.DisplayAlerts = False
'Deletes Compilation worksheet if it exists
On Error Resume Next
ActiveWorkbook.Worksheets("Compilation").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'Add a worksheet with the name "Compilation"
Set DestSh = ActiveWorkbook.Worksheets.Add
'loop through all worksheets
For Each Sh In ActiveWorkbook.Worksheets
'Loop through all worksheets except Compilation
If IsError(Application.Match(Sh.Name, _
Array(DestSh.Name), 0)) Then
'Check for the last column on row 6
lastcol = Sh.Cells(6, Columns.Count).End(xlToLeft).Column
'Check for the last row that the last column above has
lastrow = Sh.Cells(Rows.Count, lastcol).End(xlUp).Row
'Checks if Cell B3, contains JAN and then enters the contents to DestSh
If Sh.Cells(3, 2).Value Like "*JAN*" Then
destrow = DestSh.Cells(3, 2).End(xlUp).Row
prevval = prevval
nextval = prevval + Sh.Cells(lastrow, lastcol).Value
DestSh.Cells(destrow + 2, 2).Value = nextval
prevval = nextval
End If
If Sh.Cells(3, 2).Value Like "*FEB*" Then
destrow = DestSh.Cells(3, 3).End(xlUp).Row
prevval = prevval
nextval = prevval + Sh.Cells(lastrow, lastcol).Value
DestSh.Cells(destrow + 2, 3).Value = nextval
prevval = nextval
End If
End If
Next
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
答案 0 :(得分:1)
鉴于我的新手近视,我没有看到明显的。谢谢@TimWilliams
将格式更改为if和then语句:
If Sh.Cells(3, 2).Value Like "*JAN*" Then
destrow = DestSh.Cells(3, 2).Row
DestSh.Cells(destrow, 2).Value = DestSh.Cells(destrow, 2).Value _
+ Sh.Cells(lastrow, lastcol).Value
End If