我编写了一个宏,它将删除列“U”(或 column21)上非空白的任何内容,包括整个行,在名为“POL”的工作表中
根据您的描述,我将执行以下操作:
Option Explicit
Dim wb As Workbook
Dim sRng As Range
Dim fRng As Range
Dim cel As Range
Dim tRow As Long
Dim fCol As Long
Sub foo()
'setting wb as thisworkbook
Set wb = ThisWorkbook
'row 1 assigned into fRng(find range) object
Set fRng = wb.Sheets("POL").Rows(1).Find(what:="Vessel Departed from Port of Loading", LookIn:=xlValues, lookat:=xlWhole)
'gets fRng range object, and assigns its column property value into fCol variable
fCol = fRng.Column
'finding the last row for column 1, make sure you select a col that covers the whole data set, based on last row
tRow = wb.Sheets("POL").Cells(Rows.Count, 1).End(xlUp).Row
'assigning range based on col index based on str search(fCol) + total row count (tRow) in sRng range object
With wb.Sheets("POL")
Set sRng = .Range(.Cells(1, fCol), .Cells(tRow, fCol))
End With
'call sub deltR, the function does a filter based on range, string, and col number passed as argument.
'passing arguments: range (sRng), delete anything not empty, on col#1 (sRng has only one range = columns("U:U" + tRow)
Call deltR(sRng, "<>", 1)
End Sub
Private Sub deltR(ByRef sRng As Range, ByVal aStr As String, ByVal f As Integer)
'this sub procedure looks for a string (aStr) passed in (sRng) range object range, based on col number (f)
With sRng
.AutoFilter field:=f, Criteria1:=aStr
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
wb.Sheets("POL").AutoFilterMode = False
Set sRng = Nothing
End Sub
只需运行子过程“foo()”即可运行脚本。
我根据您上面编写的代码将工作表命名为“POL”。我不知道您的工作簿的结构如何。所以我根据你的解释猜测了
试一试,然后在 cmets 中与我联系以解决可能出现的问题。
更新:请再次检查,我创建了一个额外的范围对象,它在第 1 行搜索“从装货港出发的船只”字符串,并返回 col 索引
最后我也删除了“set wb = nothing”。我想这可能是导致我在 cmets 中读到的错误。
再试一次,如果您有任何问题,请告诉我。
谢谢