【问题标题】:excel vba scan col z to col a, delete if col header doesn't match set of values delete columnexcel vba扫描col z到col a,如果col标题与一组值不匹配则删除删除列
【发布时间】:2019-04-03 21:03:25
【问题描述】:

我正在尝试扫描列 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

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

【问题讨论】:

  • OR 不能那样工作。
  • 你只需要If .Cells(2, j).Value &lt;&gt; "Name" Or .Cells(2, j).Value &lt;&gt; "F/N" etcws 已定义为工作表变量。但我同意 BigBen 关于 SC 的看法。
  • Select Case 可能是更简洁的选择。

标签: excel vba multiple-columns


【解决方案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


【讨论】:

  • 大约有 25 列,我只想保留' "Name" "F/N" "Ref Des" "Component Location" "Qty" '是我想保留的列,我不确定如何对这些值中的任何一个进行循环扫描并删除不在该列表中的列。抱歉,如果不清楚
猜你喜欢
  • 1970-01-01
  • 2019-06-19
  • 2021-04-07
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 2014-03-13
  • 2020-01-08
  • 2021-09-17
相关资源
最近更新 更多