VBA:如何引用使用表标题的列,以便我可以在单元格引用中使用该列

所以基本上我有一个代码,旨在查找和删除行,如果他们有两列满足一定的条件。 但是,这些列在表中的位置通常是可变的,所以我需要使用它们的表头名称来引用这两列。 我有一个方法来使用列号来查找和删除这些行,但适应它的列名称不以相同的方式工作。 我如何调整我的代码,使其工作? 我可以使用FIND函数吗? 提前致谢!

码:

1 Sub try() 2 3 ThisWorkbook.Sheets("report").Activate 4 Last1 = Cells(Rows.Count, "A").End(xlUp).Row 5 For p = Last1 To 1 Step -1 6 If (Cells(p, "Table1[type]").Text) = "active" And (Cells(p, "Table1[data]")) <> "" Then 7 Cells(p, "A").EntireRow.Delete 8 End If 9 Next p 10 End Sub 

试试这个:

 Sub try() Dim Last1 As Long Dim colType As Integer, colData As Integer With ThisWorkbook.Sheets("report") Last1 = .Cells(.Rows.Count, "A").End(xlUp).Row colType = .Range("Table1[type]").Column colData = .Range("Table1[data]").Column For p = Last1 To 1 Step -1 If .Cells(p, colType) = "active" And .Cells(p, colData) <> "" Then .Cells(p, "A").EntireRow.Delete End If Next p End With End Sub 

顺便说一句,如果你的表有很多行,下一个代码会更有效率:

 Sub test2() Dim rng As Range Dim i As Long With ThisWorkbook.Sheets("report").ListObjects("Table1") .Range.AutoFilter .Range.AutoFilter Field:=.ListColumns("type").Index, _ Criteria1:="=active" .Range.AutoFilter Field:=.ListColumns("data").Index, _ Criteria1:="<>" .Range.Offset(1).EntireRow.Delete .Range.AutoFilter End With End Sub