excel - 循环比较列中的值,如果不同则插入新行,但如果第一行是唯一值则忽略第一行
问题描述
我正在对库存页面进行排序,并在排序后分离尺寸以使其更易于阅读。
如果顶行具有唯一值(该项目只有一行),则它不会在其后插入一行,而是将其与下一组值分组。
如果有超过 1 行具有该最高值,则它会在该组之后正确插入一行。
Private Sub CommandButton1_Click()
' sort by size then length
With ActiveSheet.Sort
.SortFields.Clear
.SortFields.Add Key:=Selection.Columns(3), Order:=xlDescending
.SortFields.Add Key:=Selection.Columns(4), Order:=xlDescending
.SetRange Selection
.Apply
End With
' insert rows between sizes
Dim iRow As Integer, iCol As Integer
Dim oRng As Range
Set oRng = Range("D9")
iRow = oRng.Row
iCol = oRng.Column
Do
If Cells(iRow + 1, iCol) <> Cells(iRow, iCol) Then
Cells(iRow + 1, iCol).EntireRow.Insert shift = xlDown
iRow = iRow + 2
Else
iRow = iRow + 1
End If
Loop While Not Cells(iRow, iCol).Text = ""
End Sub
它最终看起来像这样:https ://i.imgur.com/AfYXbuF.png
如何让它在该最高值之后插入一行?
解决方案
我会稍微简化一下方法。
Private Sub CommandButton1_Click()
Dim iRow As Long
Dim oRng As Range
Set oRng = Range("D9", Range("D" & Rows.Count).End(xlUp))
For iRow = oRng.Count To 2 Step -1
If oRng.Cells(iRow) <> oRng.Cells(iRow - 1) Then
oRng.Cells(iRow).EntireRow.Insert shift:=xlDown
End If
Next iRow
End Sub
推荐阅读
- c - 如何从c中的文件中正确读取某些字符串?
- python - Discord bot 从所有渠道检索引脚
- c - 实现 `memcpy()`:是否需要`unsigned char *`,还是只需要`char *`?
- excel - 用于读取和输出自定义日期分组的嵌套 IF 语句
- ruby - 尝试使用 Gmail 的 Ruby API 修改标签时出现“错误未指定添加或删除标签”
- javascript - 由于 CORS 问题,如何修复 Google API,无法通过 JavaScript 获取?
- c - malloc 和 sizeof 时出现分段错误
- r - 如何用 r 创建世界街道地图?
- java - How to determine program complexity in Big-O when adding to a full ArrayList?
- javascript - jquery 在点击提交时获取答案(从数据库中获取数据)