我在一个工作簿中有多个工作表,每个工作表中的值为5行5列。我需要在每个工作表中添加相应的单元格值(例如:D5)并将其转储到D5中的新工作表中。我可以为一个特定的单元格做这件事,但我对如何在嵌套for循环中这样做感到困惑。我只做了一天的vba ..所以请帮忙。感谢。
Sub Macro1()
Dim i, val
'Select worksheets
For i = 7 To Sheets.Count
val = val + Sheets(i).Range("e6")
Next
Sheets("Summation").Range("e6") = val
End Sub
答案 0 :(得分:1)
这是你想要的吗?
Sub Sample()
Dim ws As Worksheet, wsSumry As Worksheet
Dim startRow As Long, StartCol As Long
Dim i As Long, j As Long
Dim ar(1 To 4, 1 To 4) As Variant
'~~> Start row and start column
startRow = 2: StartCol = 2
'~~> Summary sheet
Set wsSumry = Sheet1
'~~> Looping through each worksheet
For Each ws In ThisWorkbook.Worksheets
'~~> Check if it is not the summary sheet
If ws.Name <> wsSumry.Name Then
'~~> Loop through the row and columns and
'~~> Store it in an array
For i = startRow To (startRow + 3)
For j = StartCol To (StartCol + 3)
ar(i - 1, j - 1) = ar(i - 1, j - 1) + ws.Cells(i, j)
Next j
Next i
End If
Next
'~~> Write array to summary sheet
wsSumry.Range("B2").Resize(UBound(ar), UBound(ar)).Value = ar
End Sub
答案 1 :(得分:0)
您可以使用复制和添加技术,循环浏览不是summisary表格的每张纸张,然后将其值粘贴到最终纸张中(同时添加它们) - 类似于:
Dim b As Worksheet
Set b = ThisWorkbook.Worksheets("Sheet4")
b.range("A1:A2").clear
For Each a In ThisWorkbook.Sheets
If Not a.Name = b.Name Then
a.Range("A1:A2").Copy
b.Range("A1:A2").PasteSpecial operation:=xlAdd
End If
Next
显然,您的范围可以定义为“A1:A2”
我确信有更多的“代码”方式可以将数组添加到一起,但在Excel中这可能对你有用。