使用列标题而不是列号的参考列范围

时间:2018-03-08 09:31:47

标签: excel vba

Sub Test1()
Dim LastRow As Range
Dim cfind As Range
'Set WS = ActiveWorkbook.Worksheets("Report")
    'With WS
        'Set cfind = Cells.Find(what:="Order Status", lookat:=xlWhole, MatchCase:=False)
    'End With
LastRow = Cells(Rows.Count, "C").End(xlUp).Row

    For i = LastRow To 2 Step -1
        If Range("C" & i).Value = "Canceled" Then
            Range("C" & i).EntireRow.Delete
        End If
    Next i
End Sub

我正在尝试删除具有值"已取消"的行。在具有标题"订单状态"的列中。我目前正在使用列号或名称。我不知道如何使用列标题(订单状态)来删除行。 有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

你的LastRow是一个范围对象,应该很长。

Sub Test1()
    'not necessary now but should have been a long
    'Dim LastRow As long
    'not necessary now
    'Dim cfind As Range
    Dim col As Variant

    With ActiveWorkbook.Worksheets("Report")
        col = Application.Match("Order Status", .Rows(1), 0)
        If Not IsError(col) Then
            For i = .Cells(.Rows.Count, col).End(xlUp).Row To 2 Step -1
                If .Cells(i, col).Value = "Canceled" Then
                    .Rows(i).EntireRow.Delete
                End If
            Next i
        else
            msgbox "no 'Order Status' here"
        End If
    end with
End Sub