好的,就这样。我有一本每天都有单独工作表的工作簿,详细介绍了股票交易活动。我目前还拥有一个VBA,它可以为每个工作表上的指定列提供总计,并且效果很好。
但是,我要添加到VBA中,以便为主工作表中的这些列提供总计。
因此,例如:如果工作表1上的交易活动在2018年10月1日总计为400万,而工作表2上的交易活动在2018年10月2日总计为300万,我希望将这700万工作表。
我在下面附加了我当前的vba,每个工作表上当前合计的列为J。单个工作表上合计的列不变,但是这些列中包含的数据量显然取决于交易活动。
Sub autoSum_AllSheets()
Dim ws As Worksheet
Dim cel1 As String, cel2 As String
Dim firstCel As Range
For Each ws In ActiveWorkbook.Worksheets
With ws
Set firstCel = .Range("J3").End(xlDown).Offset(2, 0)
cel1 = firstCel.Offset(-2, 0).End(xlUp).Address
cel2 = firstCel.Offset(-1).Address
firstCel.Value = "=SUM(" & cel1 & ":" & cel2 & ")"
End With
Next ws
End Sub
我还附上了从任意一天中获取的当前模拟工作表的屏幕截图,其中将运行vba后获得的总金额加粗并用红色突出显示。
任何有关如何解决此问题的建议都非常有用,因为我是VBA所有事物的新手。
编辑:我在下面的主工作表上附有我要实现的模拟屏幕截图:
答案 0 :(得分:1)
我建议以下...
Option Explicit
Public Sub AutoSumAllWorkheets()
Const MasterName As String = "Master" 'specify name of master sheet
Dim wsMaster As Worksheet
On Error Resume Next 'test if master exists
Set wsMaster = ActiveWorkbook.Worksheets(MasterName)
On Error GoTo 0
If wsMaster Is Nothing Then 'add master if not exists
Set wsMaster = ActiveWorkbook.Worksheets.Add(Before:=ActiveWorkbook.Worksheets(1))
wsMaster.Name = MasterName
'instead you can throw a message and exit here
'MsgBox "No master found"
'Exit Sub
End If
Dim FirstCell As Range, LastCell As Range
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
If .Name <> MasterName Then 'don't sum on master sheet
Set FirstCell = .Range("J3")
Set LastCell = FirstCell.End(xlDown)
LastCell.Offset(2, 0).Formula = "=SUM(" & FirstCell.Address & ":" & LastCell.Address & ")"
'write in master
With wsMaster.Cells(wsMaster.Rows.Count, "A").End(xlUp)
.Offset(1, 0).Value = ws.Name
.Offset(1, 1).Formula = "=" & LastCell.Offset(2, 0).Address(External:=True)
End With
End If
End With
Next ws
'sum all sheets up
With wsMaster.Cells(wsMaster.Rows.Count, "A").End(xlUp)
.Offset(2, 0).Value = "Total sum:"
.Offset(2, 1).Formula = "=SUM(" & wsMaster.Cells(1, "B").Address & ":" & .Offset(0, 1).Address & ")"
End With
End Sub
第一部分检查母版是否存在,如果不存在则添加一个。
然后我对您的代码做了一些改进:
firstCel
实际上不是第一个,而是求和单元格。这非常令人困惑,您很容易失败。.Formula
编写公式。如果要写入母版表的另一列,只需将wsMaster.Cells(wsMaster.Rows.Count, "A").End(xlUp)
的列名从"A"
更改为"L"
答案 1 :(得分:0)
尝试:
Sub test4()
Dim ws As Worksheet
Dim LastRowJ As Long
Dim MasterTotal As Double
For Each ws In ActiveWorkbook.Worksheets
LastRowJ = ws.Cells(ws.Rows.Count, "J").End(xlUp).Row
MasterTotal = MasterTotal + ws.Range("J" & LastRowJ).Value '<= Let us assume that total appears in each sheet at the last line in column J
Next ws
Sheet1.Range("A1").Value = MasterTotal '<= Change where you want to import the total of totals
End Sub