excel vba:只有在列标题满足条件时才对行进行求和

我有一个电子表格,其中销售数据与N:AD列中的其他数据交织在一起。 销售栏目的标题总是以“Sales”一词结尾(例如,“2015-06-Sales”),我希望数据只在标题以“Sales”结尾时才为每行计算总和。因为列名会随时间变化。

示例数据(我希望列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 

它创build运行时错误'1004':对象'_Global'的方法'范围'在开始的行上失败“如果正确(范围…

我感谢任何帮助!

试试这个:

 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 

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

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

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

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