2017-04-08 126 views
0

我正在編寫一個代碼,用於搜索列B中名稱的更改,然後根據列中的變量數據插入行和公式E:J當名稱更改爲某人時新(新值在細胞中)。有些名字不止一次列出,但是在B列中連續列出,我想將它們組合在一起,每個人總共有一個名字,但是現在每次在列B中存在任何數據時總共執行一次,而不是每次名稱變化。我遇到的另一個問題是它並沒有總計最後一個人,因爲除了姓氏之外,B列中沒有空格,所以沒有什麼會改變來激活「THEN」。我很感激我對代碼的任何反饋。以下是我目前有:存儲單元格值但排除空單元格:

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

你可以考慮不同的方法:

  • 通過從最後一個相反的順序排循環到第一個

  • 使用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