【问题标题】:Insert a row in Excel by analyzing the values通过分析值在 Excel 中插入一行
【发布时间】:2014-08-11 14:37:57
【问题描述】:

我有一个带有数字和文本的巨大电子表格。 第一列如下所示:

1111
1111
2222
2222
2222
3333
3333
3333

我想在新唯一编号的开始处插入一个空白行。即当 222222 在 111 之后开始时,我想插入一个空白行。

【问题讨论】:

  • 可能是错误的,但我认为您需要 VBA 来执行此操作。您愿意添加 Excel-VBA 标签,还是只对非 VBA 解决方案感兴趣?
  • 嗨 Rick 是的,如果没有其他快捷方式,请告诉我 vba 代码。

标签: excel insert row vba


【解决方案1】:

这就是你要找的。​​p>

Sub InsertRows()
Dim i, RowVal1, RowVal2
i = 1
Do
RowVal1 = Worksheets("Sheet1").Cells(i, 1).Value
RowVal2 = Worksheets("Sheet1").Cells(i + 1, 1).Value
If RowVal1 <> RowVal2 Then
Worksheets("Sheet1").Cells(i + 1, 1).EntireRow.Insert
i = i + 1
End If
i = i + 1
Loop While (RowVal2 <> "")
End Sub

【讨论】:

    【解决方案2】:

    这类问题经常出现,我希望 VBA 允许更高阶的函数,这样 Insert 可以只用一个委托代替。

    Sub SeparateByID(ByRef rng as Range, ByVal id_col as Variant)
    
        Dim row_count as Integer
        row_count = rng.Rows.Count
    
        Dim last_id As Variant
        last_id = rng.cells(row_count , id_col).value
    
        Dim row_index as Integer
        For row_index = row_count To 1 Step -1
    
            Dim crnt_id As Variant
            crnt_id = rng.cells(row_index, id_col).value
    
            If last_id <> crnt_id Then 
    
                rng.cells(row_index + 1, id_col).EntireRow.Insert shift:=xlDown
                last_id = crnt_id 
    
            End If
    
        Next row_index 
    
    End Sub
    

    注意:范围应预先排序。

    一些尝试实现委托...

    Sub InsertNewRow(rng as Range)
    
        rng.EntireRow.Insert shift:=xlDown
    
    End Sub
    
    Sub DoBetweenIDs(ByRef rng as Range, ByVal id_col as Variant, ByVal delegate As String)
    
        Dim row_count as Integer
        row_count = rng.Rows.Count
    
        Dim last_id As Variant
        last_id = rng.cells(row_count , id_col).value
    
        Dim row_index as Integer
        For row_index = row_count To 1 Step -1
    
            Dim crnt_id As Variant
            crnt_id = rng.cells(row_index, id_col).value
    
            If last_id <> crnt_id Then 
    
                Application.Run delegate, rng.cells(row_index + 1, id_col)
                last_id = crnt_id
    
            End If
    
        Next row_index 
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      相关资源
      最近更新 更多