简体   繁体   English

Excel-VBA命名范围行总和

[英]Excel-VBA Named range row sum

I have the following code 我有以下代码

 For i = 1 To DepRng.Rows.Count
    For j = 1 To DepRng.Columns.Count
         DepRng.Cells(i, j) = Application.Sum(KidsRng.Row(i)) //Does not work
    Next j
 Next i

Although I know is wrong, i have no idea how to get it to store in DepRng.Cells(i, j) the total sum of the whole KidsRng.Row[i] Any help? 尽管我知道是错的,但我不知道如何将其存储在DepRng.Cells(i, j)中,将整个KidsRng.Row[i]的总数求和。

The following code works ok. 以下代码可以正常工作。

Perhaps you should compare it with yours: 也许您应该将其与您的相比较:

Sub a()

Dim DepRng As Range
Dim kidsrng As Range
Set DepRng = Range("B1:B2")
Set kidsrng = Range("C1:F2")

 For i = 1 To DepRng.Rows.Count
      DepRng.Cells(i, 1) = Application.Sum(kidsrng.Rows(i))
 Next i

End Sub

Just fill the range C1:F2 with numbers and the totals per row will appear in B1:B2 upon execution of the macro. 只需用数字填充范围C1:F2,每行的总和将在执行宏后显示在B1:B2中。

排序,谢谢大家的帮助

   DepRng.Cells(i, j) = Application.Sum(KidsRng.Rows(i)) //just needed to add the "s" in rows

There may be a better way than this, but this is my solution which depends on the internal Excel formula engine though, it might be sufficient enough for what you're doing... It determines the full address of KidsRng.Row(i), and feeds it into a =SUM() formula string and evaluated by Application.Evaluate. 也许有比这更好的方法,但是这是我的解决方案,尽管它取决于内部Excel公式引擎,但对于您正在执行的操作来说可能就足够了...它确定了KidsRng.Row(i)的完整地址,并将其输入= SUM()公式字符串中,并由Application.Evaluate进行评估。

For i = 1 To DepRng.Rows.Count
    For j = 1 To DepRng.Columns.Count

        DepRng.Cells(i, j).Value = Application.Evaluate("=SUM(" & KidsRng.Row(i).Address(True, True, xlA1, True) & ")")

    Next j
 Next i

updated it to work if kidsrng existed in a different sheet/book updated to use Application.Evaluate 如果在更新为使用Application的另一张图纸/书中存在kidsrng,则对其进行了更新,以进行工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM