我在A列中有数字。我正在尝试开发VBA代码以搜索A列中的每个数字,并在A列中有数字后删除上面的一行。例如:
A18中的数字->删除第17行
A21中的数字->删除第20行
A33中的数字->删除第32行
此代码用于在A列中的值上方插入一行。我试图将其修改为删除:
Dim r6 As Range, r7 As Range
Set printareaP = ThisWorkbook.Worksheets("Pricelist")
With printareaP.Range("Print_Area")
For Each r6 In .Range("A1", .Range("A" & Rows.Count).End(xlUp))
If Not IsEmpty(r6.Value) Then
If r7 Is Nothing Then
Set r7 = r6
Else
Set r7 = Union(r7, r6)
End If
End If
Next r6
If r7 Is Nothing Then
Else
r7.EntireRow.Delete
End If
我收到以下错误消息:
Set r7 = Union(r7, r6)
----------------编辑------------------------------ -----------------
我想出了以下代码:
With printareaP.Range("Print_Area")
For Each Cell In .Range("A1", .Range("A" & Rows.Count).End(xlUp))
If Not IsEmpty(Cell.Value) Then
.Cells(Cell.Row - 1, 1).EntireRow.Delete
End If
Next
End With
答案 0 :(得分:2)
这是我的建议:
Option Explicit
Sub test()
Dim r6 As Range, r7 As Range
Dim ws As Worksheet
Dim LastRow As Long
Dim printareaP As Range, Cell As Range
Set ws = ThisWorkbook.Worksheets("Pricelist")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set printareaP = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, 1))
For Each Cell In printareaP
If IsNumeric(Cell.Value) Then
ws.Cells(Cell.Row - 1, 1).EntireRow.Delete
End If
Next Cell
End Sub
答案 1 :(得分:1)
假定 Print_Area 包含 A 列的相关部分。否则,请从代码中删除.Range("Print_Area")
。
Sub DeleteRowAbove()
Dim r6 As Range, r7 As Range
With ThisWorkbook.Worksheets("Pricelist").Range("Print_Area")
For Each r6 In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
If Not IsEmpty(r6) And IsNumeric(r6) Then
If r7 Is Nothing Then
Set r7 = r6.Offset(-1, 0)
Else
Set r7 = Union(r7, r6.Offset(-1, 0))
End If
End If
Next
End With
If Not r7 Is Nothing Then
r7.EntireRow.Delete ' .Hidden = True
Set r7 = Nothing
End If
End Sub
好方法。继续努力。