【问题标题】:excel vba: Summing values in a row only when column heading meets a conditionexcel vba:仅当列标题满足条件时才对一行中的值求和
【发布时间】:2015-09-01 05:47:59
【问题描述】:

我有一个电子表格,其中销售数据与 N:AD 列中的其他数据穿插在一起。 sales 的列标题始终以 Sales 一词结尾(例如,“2015-06-Sales”。我希望仅当标题以“Sales”一词结尾时才对每一行的数据求和。我需要这样做vba,因为列名会随着时间而变化。

示例数据(我希望 F 列对以 sales 结尾的列进行求和 - 或者在下面的例子中为 N 和 P):

       Column F     Column N        Column O     Column P
       Total Sales  2015-05-Sales   2015-05-Qty  2015-01-Sales
Item1    20            5               30            15   
Item2    15            5               1             10  
Item3    10            1               2             9 

这是我目前的代码:

Sub test()
Dim lcolumn As Long
Dim lrow As Long
Dim SSold

For lrow = 2 To 100 Step 1
    For lcolumn = 14 To 30 Step 1
        If Right(ws.Range(1 & lcolumn), 5).Value = "Sales" Then
            SSold = 0
            SSold = SSold + Range(lrow & lcolumn)
        End If
    Next lcolumn
    Range(lrow & 6).Value = SSold
Next lrow

End Sub

它创建运行时错误“1004”:对象“_Global”的方法“范围”在“如果正确(范围...

感谢您的帮助!

【问题讨论】:

  • 在几个地方将Range(lrow & lcolumn) 替换为Cells(lrow, lcolumn)Range.Cells property 接受行和列的数字参数。 Range object 需要 xlA1 样式的单元格引用。
  • 我也想知道你为什么每次找到匹配项时都要重置SSold = 0。看来 ti 永远不会收集总数;只有最后一个匹配的值。
  • @Jeeped 不是每列总计的OP重置值吗?
  • @mrbungle - 也许我没有正确阅读,但在我看来 SSold 在添加任何新值之前立即重置为零。
  • SSold 每次都会保留该值,并继续添加到自身而不是重置为 0 以总计每一列。从一开始就设置为零也是我这样做的方式。我已经体验过 excel 保留上一次运行代码的值。

标签: vba excel


【解决方案1】:

试试这个:

Sub SumSales()
    Dim total As Double

    For iRow = 2 To 100      'no need of Step 1, test as many rows as you wish
        total = 0            'resets the total for each row
        For iCol = 14 To 30  'tests as many columns as you wish
            If Right(Cells(1, iCol).Value, 5) = "Sales" Then
                total = total + Cells(iRow, iCol).Value
            End If
        Next iCol            'this loop will go on for each column in iRow row
        Cells(iRow, 6).Value = total  'store the total before going to the next row
    Next iRow
End Sub

【讨论】:

  • 谢谢!太完美了!
【解决方案2】:

Range 采用“A2”样式范围定义。范围(列、行)

If Right(ws.Range("A" & lrow), 5).Value = "Sales" Then

如果您需要使用数字,请尝试使用单元格。单元格(行、列)

If Right(ws.Cells(1 & lcolumn), 5).Value = "Sales" Then

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2020-01-10
    • 2021-04-02
    • 2021-08-02
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多