我编写了一个VBA脚本,允许用户允许将新程序集及其权重插入表中。插入的组件可以是两个级别(1或2)中的一个。如果插入的行是子组件(即级别2),则其位置直接位于较高级组件的下方。我希望1级权重等于所有2级权重的总和。我认为最简单的方法是通过计算空白单元格来定义范围,然后进行计算。如果当前在级别1中的权重与级别2权重之和之间的差异不为0,我希望将该值作为级别2权重插入与级别1组件相同的行中。我意识到这是相当令人困惑的,所以附上了一张图片试图稍微更好地解释它。任何帮助表示赞赏:)
以下是我目前用于插入值的代码(来自用户表单)
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
答案 0 :(得分:1)
好的,就在这里。使用此宏。完成程序集的工作后执行它。
代码说明:
只需将其作为宏执行一次。将设置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