基于Excel中的两行或更多行获取行上的值

时间:2016-01-09 11:27:47

标签: excel vba

我在DEMAND行中的值和COLLECTION行中的值,现在我想要BALANCE = DEMAND-COLLECTION,有两次收集的条目,所以根据收集的发生,应该出现余额。你能告诉我宏代码吗。

我有DEMAND值D1:来自D2:S2的S1 COLLECTION值,余额应该在下一行。

在我得到解决方案之后,我来到了这一步 Insert row base on specific text and its occurrence

我正在使用以下代码

Sub try()
 Dim c As Range
 Dim lRow As Long
 lRow = 1
 Dim lRowLast As Long
 Dim bFound As Boolean
 With ActiveSheet
  lRowLast = .Cells(.Rows.Count, 1).End(xlUp).Row
  Do
   Set c = .Range("A" & lRow)
   If c.Value Like "*COLLECTION*" Then
    bFound = True
   ElseIf bFound Then
    bFound = False
    If c.Value <> "BALANCE" Then
     c.EntireRow.Insert
     lRowLast = lRowLast + 1
     c.Offset(-1, 0).Value = "BALANCE"
     c.Offset(-1, 0).Font.Color = RGB(0, 0, 0)
    End If
   End If
   lRow = lRow + 1
  Loop While lRow <= lRowLast + 1
 End With
End Sub

before macro check IMAGE

After Macro I want this check image

1 个答案:

答案 0 :(得分:0)

因此,我会将SUMIFFormulaR1C1一起使用。优点是我们可以为整行设置一步的公式。

Sub try()
 Dim c As Range
 Dim lRow As Long
 lRow = 1
 Dim lRowLast As Long
 Dim lRowDiff As Long
 Dim lRowPortion As Long
 lRowPortion = 1
 Dim bFoundCollection As Boolean
 With ActiveSheet
  lRowLast = .Cells(.Rows.Count, 1).End(xlUp).Row
  Do
   Set c = .Range("A" & lRow)
   If c.Value Like "*COLLECTION*" Then
    bFoundCollection = True
   ElseIf bFoundCollection Then
    bFoundCollection = False
    If c.Value <> "BALANCE" Then
     c.EntireRow.Insert
     lRowLast = lRowLast + 1
     Set c = c.Offset(-1, 0)
     c.Value = "BALANCE"
    End If
    If c.Value = "BALANCE" Then
     .Range(c, c.Offset(0, 18)).Font.Color = RGB(0, 0, 0)
     .Range(c, c.Offset(0, 18)).Interior.Color = RGB(200, 200, 200)
     lRowDiff = c.Row - lRowPortion
     .Range(c.Offset(0, 3), c.Offset(0, 18)).FormulaR1C1 = _
      "=SUMIF(R[-" & lRowDiff & "]C1:RC1, ""*DEMAND*"", R[-" & lRowDiff & "]C:RC)" & _
      "-SUMIF(R[-" & lRowDiff & "]C1:RC1, ""*COLLECTION*"", R[-" & lRowDiff & "]C:RC)"
     lRowPortion = c.Row + 1
    End If
   End If
   lRow = lRow + 1
  Loop While lRow <= lRowLast + 1
 End With
End Sub