excel vba:仅当列标题满足条件时才对行中的值求和

时间:2015-08-31 21:33:29

标签: excel vba excel-vba

我有一个电子表格,其中销售数据散布在N:AD列中的其他数据中。销售的列标题总是以Sales字样结束(例如," 2015-06-Sales"。我希望数据仅在标题结束时的每一行汇总#34; Sales& #34;。我需要用vba执行此操作,因为列名称会随着时间的推移而变化。

示例数据(我希望列F将以销售结束的列相加 - 或者在下面的情况下为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'在开始的线路上失败"如果正确(范围......

我感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

请改为尝试:

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

答案 1 :(得分:2)

范围需要" A2"样式范围定义。范围(列,行)

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

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

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