如何在多张纸上添加?

时间:2019-06-05 19:03:09

标签: excel vba

我正在尝试在一个工​​作簿的多个工作表中添加相同的单元格。一些参数:

  • 单元格将始终相同(A4)
  • 我不确定每个月有多少张纸。
  • 它存储为数字吗?

我尝试使用谷歌搜索,它总是有一个简单的求和公式。我希望专门编写一个VBA函数来实现它。

Function AddAcrossSheets(rng As Range) As Variant

    valRow = rng.Row
    valCol = rng.Column


    For x = 1 To Sheets.Count
        AddAcrossSheets = Sheets(x).Cells(valRow, valCol).Value + AddAcrossSheets
    Next x


End Function

2 个答案:

答案 0 :(得分:0)

请记住,始终在代码的顶部添加Option Explicit。这将迫使您声明所有变量,从而使您免于各种麻烦。

这就是我要做的

Sub addAcrossSheets()
Dim sht As Worksheet
Dim totalSum As Double
totalSum = 0 'initialize the sum
For Each sht In ThisWorkbook.Worksheets 'loop through the collection of worksheets
    totalSum = totalSum + sht.Range("A4") 'update the sum
Next sht
Debug.Print totalSum 'the result is displayed in your immediate window
End Sub

现在,您可能要从总和中排除一些工作表。您可以这样做:

For Each sht In ThisWorkbook.Worksheets 'loop through the collection of worksheets
    If sht.Name <> "Something" And sht.Name <> "Something else" Then 'exclude worksheets from the sum
        totalSum = totalSum + sht.Range("A4") 'update the sum
    End If
Next sht

答案 1 :(得分:-1)

如果位置(A4)始终相同,则只需将其硬编码即可。

valueFromA4 = Cells(4, 1).Value

For i = 2 To Sheets.Count
    Sheets(i).Cells(4, 1).Value = valueFromA4
Next i

我建议您在for循环中使用i,这只是一个约定。大多数循环以i = 0开头,但是Excel工作表以1开始计数,因此第一张工作表之后的工作表为2。

相关问题