VBA数组删除整个列

时间:2016-02-29 20:33:03

标签: arrays excel vba excel-vba

此代码试图删除包含与数组(列表)中的“文本”匹配的标题行的列。

代码根据第一个数组值"标题文本1"成功删除列。

问题发生在A.EntireColumn.Delete上的第二轮循环期间。当我打印vItem时,它会显示预期的“标题文本2”值,这是数组中的正确项。

  

VBA错误 - 运行时错误'91'

     

对象变量或未设置块变量

Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")

For Each vItem In ColumnsToRemove

    Set A = Rows(1).Find(What:=(ColumnsToRemove), LookIn:=xlValues, lookat:=xlPart)
    Debug.Print vItem
    A.EntireColumn.Delete

Next
End Sub

3 个答案:

答案 0 :(得分:3)

您需要查找vItem,并且在尝试删除它所在的列之前,您需要添加一个检查以查看是否找到了它。

Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")

For Each vItem In ColumnsToRemove

    Set A = Rows(1).Find(What:=vItem, LookIn:=xlValues, _
                          lookat:=xlPart)

    Debug.Print vItem, Not A Is Nothing

    If Not A Is Nothing Then A.EntireColumn.Delete

Next
End Sub

答案 1 :(得分:1)

Sub ArraybLoop()
Dim ColumnsToRemove() As Variant
Dim vItem As Variant
Dim A As Range
Dim i As Long
Dim Sht As Worksheet

Set Sht = ActiveWorkbook.Sheets("Sheet1")

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")


    For i = LBound(ColumnsToRemove) To UBound(ColumnsToRemove) Step 1
        vItem = Application.Match(ColumnsToRemove(i), Sht.Rows(1), 0)

        Debug.Print vItem

        If IsNumeric(vItem) Then Sht.Columns(vItem).Delete
    Next i

End Sub

Upper and Lower Bounds

Understanding Arrays

答案 2 :(得分:1)

循环索引的一种方法是使用uboundlbound

Sub ArrayLoop()
Dim ColumnsToRemove As Variant
Dim vItem As Variant
Dim A As Range
Dim i As Long

ColumnsToRemove = Array("Header Text 1", "Header Text 2", "Header Text 3")


For i = LBound(ColumnsToRemove) To UBound(ColumnsToRemove)
    Set A = Rows(1).Find(what:=ColumnsToRemove(i), LookIn:=xlValues, lookat:=xlPart)
    Debug.Print ColumnsToRemove(i) ' not sure what `vItem` was intended to be
If A Is Nothing Then
    Debug.Print "Nothing found"
ElseIf Not A Is Nothing Then
    A.EntireColumn.Delete
End If
Next i

End Sub