按表头引用列而不是字母

时间:2017-11-30 17:34:59

标签: excel excel-vba vba

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

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

代码工作得很好,但我在表中使用它,所以我想用表头引用替换固定列“F”。这样,如果有人插入列,它仍然可以工作。我很难找到正确的语法。

我的表格和专栏是:

Range("PART_SELECTION_DATABASE[PART '#]")

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用Find功能查找标题PART '#"

找到后,您可以使用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
相关问题