2016-11-08 22 views
0

我有這種格式的數據: Excel DataVBA插入空行基於細胞的差異

我想基於列B和C值之間的差異添加一個空白行

我已經找到一段很好的代碼,它的工作非常出色。

Dim i, itotalrows As Integer 
Dim strRange As String 

itotalrows = ActiveSheet.Range("B65536").End(xlUp).Offset(1, 0).Row 


Do While i <= itotalrows 
    i = i + 1 
    strRange = "B" & i 
    strRange2 = "B" & i + 1 
    If Range(strRange).Text <> Range(strRange2).Text Then 
     Rows(i + 1).Insert 
     itotalrows = ActiveSheet.Range("B65536").End(xlUp).Offset(1, 0).Row 
     i = i + 1 
    End If 

Loop 

但這僅檢查在列B.我添加了C列同一個循環的差異,但我結束了對空行。我製作的代碼:

Dim i, itotalrows As Integer 
Dim strRange As String 

Dim n, itotalrowsc As Integer 
Dim strRangec As String 

itotalrows = ActiveSheet.Range("B65536").End(xlUp).Offset(1, 0).Row 
itotalrowsc = ActiveSheet.Range("C65536").End(xlUp).Offset(1, 0).Row 

Do While i <= itotalrows 
    i = i + 1 
    strRange = "B" & i 
    strRange2 = "B" & i + 1 
    If Range(strRange).Text <> Range(strRange2).Text Then 
     Rows(i + 1).Insert 
     itotalrows = ActiveSheet.Range("B65536").End(xlUp).Offset(1, 0).Row 
     i = i + 1 
    End If 

Loop 

Do While n <= itotalrowsc 
    n = n + 1 
    strRange = "C" & i 
    strRange2 = "C" & i + 1 
    If Range(strRangec).Text <> Range(strRangec2).Text Then 
     Rows(i + 1).Insert 
     itotalrows = ActiveSheet.Range("C65536").End(xlUp).Offset(1, 0).Row 
     i = i + 1 
    End If 

Loop 

它可能會考慮第一個循環中的空行和基於此的另一個空行。

我如何調整代碼有某事像這樣:

If B[i] <> B[i+1] or C[i] <> C[i+1] Then Insert BlankRow 

回答

0

嗯,而不是添加第二塊,儘量只添加For循環。 (注意:我也改變strRangeRange):

Sub t() 
Dim i, itotalrows As Integer 
Dim strRange As Range, strRange2 As Range 
Dim col As Long 

itotalrows = ActiveSheet.Range("B65536").End(xlUp).Offset(1, 0).Row 

For col = 2 To 3 
Do While i <= itotalrows 
    i = i + 1 
    Set strRange = Cells(i, col) 
    Set strRange2 = Cells(i + 1, col) 
    If strRange.Text <> strRange2.Text Then 
     Rows(i + 1).EntireRow.Insert 
     ' What's itotalrows doing? 
     itotalrows = ActiveSheet.Range("B65536").End(xlUp).Offset(1, 0).Row 
     i = i + 1 
    End If 
Loop 
Next col 
End Sub 
+0

謝謝@BruceWayne,但是你提供的代碼無法正常工作。它在第一次迭代後停止。它根據B列中2個不同的單元格添加一個空行,然後停止。 – WujekNemo