excel vba将col z扫描到col a,如果col标头与值集不匹配则删除

时间:2019-04-03 21:03:26

标签: excel vba multiple-columns

我正在尝试扫描Z到A列,如果列标题(第2行中)与设置的值列表不匹配,则删除列或范围(“ Z2:Z”&last_row等) 。

到目前为止,这是我的代码(我在网上找到了列部分,但它不起作用)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

WBPath = CreateObject("WScript.Shell").SpecialFolders("Desktop")

'scan for the line to delete row 2 , row 3, row 4 depending
For i = 6 To 2 Step -1
    If Range("A" & i) = "" Then
        Rows(i).Select
            Selection.Delete Shift:=xlUp
                End If
                    Next i

'scan columns for matching names
    Dim ws As Worksheet
    Dim j As Long
    Dim delRange As Range

    '~~> Set this to the relevant worksheet
    Set ws = ActiveSheet

    With ws
        '~~> Loop through relevant columns
        For j = 26 To 1 Step -1
            '~~> Check if the value is equal to YY
            If Worksheets(ws).Cells(2, j).Value <> "Name" Or "F/N" Or "Ref Des" Or "Component Location" Or "Qty" Then
                Columns(i).Select
            Selection.Delete Shift:=xlLeft
            End If
        Next j
    End With

此行的类型13不匹配失败

If Worksheets(ws).Cells(2, j).Value <> "Name" Or "F/N" Or "Ref Des" Or "Component Location" Or "Qty" Then

我认为我的行代码更简洁,是否有类似的列方法或更好的方法来扫描和杀死列?

1 个答案:

答案 0 :(得分:1)

您尝试使用 OR 语句的方式是错误的。

OR -表示必须满足一个条件。

AND -表示两个条件都是必需的。

尝试一下...


 '~~> Set this to the relevant worksheet
    Set ws = ActiveSheet
    With ws
        '~~> Loop through relevant columns
        For j = 26 To 1 Step -1
            '~~> Check if the value is equal to YY
            If .Cells(2, j) <> "Name" And .Cells(2, j) <> "F/N" And .Cells(2, j) <> "Ref Des" And .Cells(2, j) <> "Component Location" And .Cells(2, j) <> "Qty" Then
                Columns(j).Select
            Selection.Delete Shift:=xlLeft
            End If
        Next j
    End With