VBA Excel 删除子项
VBA Excel delete children items
我正在尝试编写一个宏,它会遍历该列并查看当前单元格是否包含来自同一列的前一行的值(从左开始读取)。下面是一个带有黄色单元格标记为删除的示例图像。例如,有一个值为“22.2”的单元格,下一个单元格包含相同的值和末尾的“.1”,这意味着它是一个子项,需要删除。
我在代码方面的想法是这样的:
Sub DeleteSubparts()
'Declare variables
Dim LastRow As String
LastRow = Cells(Rows.Count, "E").End(xlUp).Row
'Delete parts subgroup
For i = 2 To LastRow
If Cells(i, 10).Value = Left(Cells(i - 1, 10)) Then
Cells(i, 10).Value = ""
End If
Next i
End Sub
这个想法并不是最好的方法,但是“J”列中的每个值都是唯一的并且按 A-z 排序,所以这个想法应该可行。但总体目标是查看列表中是否有任何部分的子部分,如果有 - 删除该子部分。
有人可以帮我完成该代码吗?
P.S。在我的代码中,它只是为了测试而使单元格空白,但是我编写代码的方式存在一些问题。它 return 的“参数不是可选的”错误
编辑:
尝试一些似乎更正确的事情并且不会 return 错误,但仍然没有做任何不可见或无意的事情。
If Cells(i, 10).Value = Left(Cells(i - 1, 10), Len(Cells(i - 1, 10))) Then
Cells(i, 10).Value = ""
End If
这将删除包含“子”单元格的整行。
Option Explicit
Sub DeleteRows()
Dim row As Long
Const col As Integer = 10 ' col J
With Worksheets("Sheet1")
' Start on second row of data
row = 2
Do While .Cells(row, col).Value <> ""
' Use Like to compare the value of the current cell to the value of the previous cell
If .Cells(row, col).Value Like .Cells(row - 1, col).Value & ".*" Then
.Rows(row).Delete
Else
row = row + 1
End If
Loop
End With
End Sub
或者这只会清除子单元格的内容。
If .Cells(row, col).Value Like .Cells(row - 1, col).Value & ".*" Then
.Cells(row, col).Clear
End If
row = row + 1
我正在尝试编写一个宏,它会遍历该列并查看当前单元格是否包含来自同一列的前一行的值(从左开始读取)。下面是一个带有黄色单元格标记为删除的示例图像。例如,有一个值为“22.2”的单元格,下一个单元格包含相同的值和末尾的“.1”,这意味着它是一个子项,需要删除。
我在代码方面的想法是这样的:
Sub DeleteSubparts()
'Declare variables
Dim LastRow As String
LastRow = Cells(Rows.Count, "E").End(xlUp).Row
'Delete parts subgroup
For i = 2 To LastRow
If Cells(i, 10).Value = Left(Cells(i - 1, 10)) Then
Cells(i, 10).Value = ""
End If
Next i
End Sub
这个想法并不是最好的方法,但是“J”列中的每个值都是唯一的并且按 A-z 排序,所以这个想法应该可行。但总体目标是查看列表中是否有任何部分的子部分,如果有 - 删除该子部分。
有人可以帮我完成该代码吗?
P.S。在我的代码中,它只是为了测试而使单元格空白,但是我编写代码的方式存在一些问题。它 return 的“参数不是可选的”错误
编辑:
尝试一些似乎更正确的事情并且不会 return 错误,但仍然没有做任何不可见或无意的事情。
If Cells(i, 10).Value = Left(Cells(i - 1, 10), Len(Cells(i - 1, 10))) Then
Cells(i, 10).Value = ""
End If
这将删除包含“子”单元格的整行。
Option Explicit
Sub DeleteRows()
Dim row As Long
Const col As Integer = 10 ' col J
With Worksheets("Sheet1")
' Start on second row of data
row = 2
Do While .Cells(row, col).Value <> ""
' Use Like to compare the value of the current cell to the value of the previous cell
If .Cells(row, col).Value Like .Cells(row - 1, col).Value & ".*" Then
.Rows(row).Delete
Else
row = row + 1
End If
Loop
End With
End Sub
或者这只会清除子单元格的内容。
If .Cells(row, col).Value Like .Cells(row - 1, col).Value & ".*" Then
.Cells(row, col).Clear
End If
row = row + 1