计算未定义范围内空白单元格的数量并对下一列中的值求和

Counting the Number of Blank Cells in an undefined range and summing the values in the next column

我编写了一个 VBA 脚本,允许用户将新程序集及其权重插入 table。插入的程序集可以是两个级别之一(1 或 2)。如果插入的行是子组件(即级别 2),则其位置直接位于更高级别组件的下方。我希望 1 级权重等于所有 2 级权重的总和。我相信最简单的方法是通过计算空白单元格来定义范围,然后进行计算。如果当前级别 1 中的权重与级别 2 权重之和之间的差异不为 0,我希望将此值作为级别 2 权重插入到与级别 1 组件相同的行中。我意识到这很令人困惑,所以附上一张图片来尝试更好地解释它。感谢任何帮助:)

Excel Sheet Image

这是我目前用来插入值的代码(来自用户表单)

If TextBox_LevelNo.Value = 1 Then
Cells(NextRow, 6).Value = TextBox_Weight.Value
Cells(NextRow, 7).Value = TextBox_ExtraWeight.Value
ElseIf TextBox_LevelNo.Value = 2 Then
Cells(NextRow, 7).Value = TextBox_Weight.Value
Cells(NextRow, 8).Value = TextBox_ExtraWeight.Value
ElseIf TextBox_LevelNo.Value = 3 Then
Cells(NextRow, 8).Value = TextBox_Weight.Value
End If

好的,开始了。使用这个宏。完成程序集的工作后执行它。

代码解释:

  • col1 和 col2 必须分别设置为级别的列号
  • 不需要其他变体。检查列值只是一次大迭代

只需将其作为宏执行一次即可。将设置级别 1 条目旁边的所有级别 2 列。

Sub SumLevelOne()

Dim col1 As Integer
Dim col2 As Integer

col1 = 1    'level 1 column (1 = A)
col2 = 2    'level 2 column (2 = B)

Dim i As Integer
Dim currentLevel1Row As Integer
currentLevel1Row = -1
Dim currentLevel1Total As Integer
currentLevel1Total = 0
Dim currentLevel2Sum As Integer
currentLevel2Sum = 0

Dim LastRow As Integer
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, col2).End(xlUp).Row

For i = 1 To LastRow
    If Cells(i, col1) <> "" Then    'level 1 entry
        If currentLevel1Row <> -1 Then  'level 1 entry already set
            'sum up former level 1 entry:
            Cells(currentLevel1Row, col2) = currentLevel1Total - currentLevel2Sum
        End If
        'set new level 1 entry
        currentLevel1Row = i
        currentLevel1Total = Cells(i, col1)
        currentLevel2Sum = 0
    ElseIf i = LastRow Then
        If currentLevel1Row <> -1 Then  'level 1 entry already set
            'sum up former level 1 entry:
            Cells(currentLevel1Row, col2) = currentLevel1Total - currentLevel2Sum
        End If
    Else
        'sum up level 2 entries
        If Cells(i, col2) <> "" Then    'level 2 entry here
            'add this
            currentLevel2Sum = currentLevel2Sum + Cells(i, col2)
        End If
    End If

Next i
End Sub