excel - Excel VBA - 如果区域中的单元格具有相同的值,则删除整行
问题描述
问题:如果“场景”列或 K 列中的所有值与“ID”列或 A 列中的同一 ID 的值相同,如何删除整行?
例如,ID 为“1”的行将被删除,因为“场景”列下的行值相同。但是 ID 为“2”的行将被保留,因为“场景”列下的行值不同。
对于每个 ID,ID 行数保持固定为 16。这意味着 ID 1 将占用 16 行,ID 2 也将占用 16 行,依此类推。
解决方案
如果您将其放入 Worksheet 私有模块中,则此代码将完成这项工作:
这不是一个直接的解决方案,正如我们所说的那样:
CountUnique(): count unique value for a range
GetLastCell4ID(): get last cell row index for an ID value
DeleteSameScenario(): real sub to do the delete job.
Option Explicit
' count unique values list from a range:
'
' ref. https://www.thesmallman.com/list-unique-items-with-vba
'
Function CountUnique(ByVal objRange As Object)
Dim varVal
Dim rng As Range, objDict As Object
Set objDict = CreateObject("scripting.dictionary")
For Each rng In objRange
varVal = objDict.Item(rng.Value)
Next
'
CountUnique = objDict.Count
'
Set rng = Nothing
Set objDict = Nothing
'
End Function
Function GetLastCell4ID(ByVal id As Long, ByVal lFirstCell As Long, ByVal nRows As Long)
Dim l As Long
l = Application.WorksheetFunction.CountIf(Range("A" & lFirstCell & ":A" & nRows), id)
GetLastCell4ID = lFirstCell + l - 1
End Function
Sub DeleteSameScenario()
Dim iRowStart As Long, iRowEnd As Long, nUnique As Long, nRows As Long
'
' get total initial non empty rows:
nRows = Cells(rows.Count, "A").End(xlUp).row
' loop over ID range:
'
iRowStart = 2
'
Do While (iRowStart < nRows)
iRowEnd = GetLastCell4ID(Range("A" & iRowStart).Value, iRowStart, nRows)
nUnique = CountUnique(Range("K" & iRowStart, "K" & iRowEnd))
If (nUnique = 1) Then
Range("A" & iRowStart & ":A" & iRowEnd).EntireRow.Delete
nRows = nRows - (iRowEnd - iRowStart + 1)
Else
iRowStart = iRowEnd + 1
End If
Loop
End Sub
推荐阅读
- java - 访问存储系统 Anylogic 中的特殊存储
- python - 突出显示 matplotlib 中的点序列
- facebook - Facebook 的客户匹配是否已弃用?
- html - 如何修复 For 循环(角度)中的输入?
- google-apps-script - Google 课堂 - 列出所有课程
- node.js - 使用 Google Cloud Vision 查找图像中特定类型的每个对象
- javascript - 矩阵(数组数组|二维数组)求和,没有循环。有更好的方法吗?
- google-sheets-api - 如何从 Google Sheets API 获取原始数字
- javascript - 添加点击事件
- vaadin-flow - 我需要在 Vaadin 中添加一个过滤器来拦截所有请求