如果数组

时间:2016-09-09 15:46:59

标签: arrays excel-vba vba excel

我在想这可能会更好地作为一个数组,但不知道如何做到这一点。我现在这样做的方式并没有产生我想要的结果:

Sub DeleteColumns_Cash()
Set dltRange = Range("A1:ZZ1")
For Each cell In dltRange
    If cell.Value <> "AMOUNT" Or cell.Value <> "TRANTYPE" Or cell.Value <> "CCY" Or cell.Value <> "SECID" Or cell.Value <> "SECDESC" Or cell.Value <> "FUND" Then
    cell.EntireColumn.Delete
    End If
Next
End Sub

2 个答案:

答案 0 :(得分:0)

Sub DeleteColumns_Cash()
    Dim arr
    arr = Array("AMOUNT", "TRANTYPE", "CCY", "SECID", "SECDESC", "FUND")
    Set dltRange = Range("A1:ZZ1")
    For Each cell In dltRange
        If IsError(Application.Match(cell.Value, arr, 0))  Then
            cell.EntireColumn.Delete
        End If
    Next
End Sub

答案 1 :(得分:0)

将条件语句更改为Select Case statement并向后循环。

Option Explicit

Sub DeleteColumns_Cash()
    Dim i As Long

    With ActiveSheet
        With .Range("A1:ZZ1")
            For i = .Columns.Count To 1 Step -1
                Select Case LCase(.Cells(1, i).Value2)
                    Case "amount", "trantype", "ccy", "secid", "secdesc", "fund"
                        'do nothing
                    Case Else
                        .Cells(1, i).EntireColumn.Delete
                End Select
            Next i
        End With
    End With

End Sub

With Activesheet更改为With Worksheets("xxxxxxx"),其中 xxxxxxx 是要处理的工作表的实际名称。