我需要一个公式或宏来在Excel中对一行混合数据求和

时间:2013-08-29 01:32:58

标签: excel vba formula

我有一列这样的数据:

Cage
1
1
1
1
1
1
1
Cage
1
1
1
1
Cage
1
1
1
1
1

我需要的是旁边的另一栏,比如说。

Cage
7
Cage
4
Cage
5

问题是信息每天都在变化,输入无法改变。 1是笼子的内容。第二天可能是:

Cage 
1
Cage
1
1
Cage
1
1
1

1 个答案:

答案 0 :(得分:0)

这是一个计算这个的程序:

Public Sub SumCages()
Dim current_row, summary_row, item_total As Integer

current_row = 1
While Sheet1.Cells(current_row, 1) <> ""
  If IsNumeric(Sheet1.Cells(current_row, 1)) Then
    item_total = item_total + Val(Sheet1.Cells(current_row, 1))
  Else
    summary_row = summary_row + 1 ' Advance summary_row
    If item_total > 0 Then
      Sheet1.Cells(summary_row, 2) = item_total ' Display total
      current_row = current_row - 1 ' Correct advancement
    Else
      Sheet1.Cells(summary_row, 2) = Sheet1.Cells(current_row, 1) ' Copy label
    End If
    item_total = 0 ' Reset item_total
  End If
  current_row = current_row + 1 ' Advance current_row
Wend
Sheet1.Cells(summary_row + 1, 2) = item_total

End Sub

enter image description here

您的数据必须符合问题细节:

  • 将非数字条目作为标签;
  • 每个标签下方的数字条目(可能与1不同)。

具体到发布的文档,以下内容产生预期的输出:

Public Sub SumCages()
Dim current_row, summary_row, item_total As Integer

current_row = 45
summary_row = 44
While Sheet8.Cells(current_row, 19) <> ""
  If IsNumeric(Sheet8.Cells(current_row, 19)) Then
    item_total = item_total + Val(Sheet8.Cells(current_row, 19))
  Else
    summary_row = summary_row + 1 ' Advance summary_row
    If item_total > 0 Then
      Sheet8.Cells(summary_row, 20) = item_total ' Display total
      current_row = current_row - 1 ' Correct advancement
    Else
      Sheet8.Cells(summary_row, 20) = Sheet8.Cells(current_row, 19) ' Copy label
    End If
    item_total = 0 ' Reset item_total
  End If
  current_row = current_row + 1 ' Advance current_row
Wend
Sheet8.Cells(summary_row + 1, 20) = item_total

End Sub