我正在编写一个代码,用于搜索B列中名称的更改,然后在名称更改为某人new(单元格中的新值)时,根据E:J列中的变量数据插入行和公式。有些名称不止一次列出,但是在B列中连续列出,我想将它们组合在一起,每人一个,但是每当B列中有任何数据时,它们总共会做一次,不只是每次更改名称。我遇到的另一个问题是它不是最后一个人,因为在姓氏后面的B列中只有空单元格,所以没有任何东西可以改变以激活"那么"。我感谢您对我的代码的任何反馈。这是我现在拥有的:
Dim firstrow As Integer
' Start on row 7 to avoid including header
row = 7
firstrow = 1
previous = Range("B7").value
While row < 1000
' Move to next row
row = row + 1
current = Range("B" & row).value
If current <> "" And current <> previous Then
Rows(row).Insert shift:=xlDown
' Formulas for Columns G, I, J, and K
Range("G" & row).Formula = "=SUM(E" & firstrow + 2 & ":G" & row - 1 & ")"
Range("I" & row).Formula = "=sum(H" & firstrow + 2 & ":I" & row - 1 & ")"
Range("J" & row).Formula = WS.Range("G" & row) - WS.Range("I" & row)
Range("K" & row).Formula = WS.Range("J" & row) / WS.Range("G" & row)
row = row
firstrow = row
End If
previous = current
Wend
答案 0 :(得分:0)
你可以考虑采用不同的方法:
从最后一行到第一行以相反顺序循环行
使用AutoFilter()
对象的Specialcells()
和Range
方法隔离连续非空单元格的块,在哪里写总计公式
如下:
Option Explicit
Sub main()
Dim iRow As Long
Dim area As Range
With Range("B1", Cells(Rows.Count, 2).End(xlUp))
For iRow = .Rows.Count To 2 Step -1
If .Cells(iRow, 1) <> .Cells(iRow + 1, 1) Then .Rows(iRow + 1).EntireRow.Insert shift:=xlDown
Next
.AutoFilter Field:=1, Criteria1:="<>"
If Application.WorksheetFunction.Subtotal(103, .Cells) > 0 Then
Set area = .SpecialCells(xlCellTypeVisible)
.Parent.AutoFilterMode = False
For Each area In area.Areas
With area.Offset(area.Rows.Count).Resize(1)
.Offset(, 5).Formula = "=SUM(" & Intersect(Range("E:G"), area.EntireRow).Address & ")"
.Offset(, 7).Formula = "=SUM(" & Intersect(Range("H:I"), area.EntireRow).Address & ")"
.Offset(, 8).FormulaR1C1 = "=RC7-RC9"
.Offset(, 9).FormulaR1C1 = "=RC10/RC7"
End With
Next
End If
End With
End Sub