通过表头而不是字母引用列

我发现下面的代码隐藏重复的行:

For i = Last_Row To First_Row Step -1 If WorksheetFunction.CountIf(Range("F" & First_Row & ":F" & i), Range("F" & i).Value) > 1 Then Rows(i).Hidden = True Next I 

代码工作的很好,但我在表中使用它,所以我想用表头参考replace固定列“F”。 这样,如果有人插入列,它仍然会工作。 我努力寻找正确的语法。

我的表和列是:

 Range("PART_SELECTION_DATABASE[PART '#]") 

任何帮助表示赞赏。

您可以使用Findfunction来查找标题PART '#"

一旦find,您可以使用FindRng.Column提取列号。

 Option Explicit Sub FindHeader() Dim FindRng As Range Dim HeadrStr As String Dim Col As Long HeadrStr = "PART '#" Set FindRng = Cells.Find(what:=HeadrStr) If Not FindRng Is Nothing Then . make sure Find was successful Col = FindRng.Column ' get the column number Else ' Find failed to find the Header MsgBox "unable to find " & HeadrStr, vbCritical Exit Sub End If For I = Last_Row To First_Row Step -1 If WorksheetFunction.CountIf(Range(Cells(First_Row, Col), Cells(I, Col)), Cells(I, Col).Value) > 1 Then Rows(I).Hidden = True Next I End Sub