【问题标题】:Get values on a row based on two or more rows in Excel根据 Excel 中的两行或多行获取一行的值
【发布时间】:2016-01-09 20:34:30
【问题描述】:

我在 DEMAND 行中有值,在 COLLECTION 行中有值,现在我想要 BALANCE = DEMAND-COLLECTION,一个条目有两次收集,因此根据收集的发生情况应该出现余额。你能告诉我那个宏代码吗?

我有 D2:S2 的 DEMAND 值 D1: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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    所以我会使用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
    

    【讨论】:

    • 应该这样做。请不要含糊其辞。说出你遇到的具体问题。
    猜你喜欢
    • 2015-07-30
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多