【发布时间】: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 <> "Name" Or .Cells(2, j).Value <> "F/N" etc。ws已定义为工作表变量。但我同意 BigBen 关于 SC 的看法。 -
Select Case可能是更简洁的选择。
标签: excel vba multiple-columns