我是VBA的初学者,在完成特定任务时需要您的帮助。实际上,我正在尝试删除表中具有数组相同元素的某些列。为此,我创建了一个数组并运行了一个双循环,以分析该数组的每个列标题。
Sub ClearColumns()
Dim Name As Variant, i As Variant, j As Variant
Name = Array("UniqueKey", "Item Type", "Path")
For j = 1 To 10
For i = 0 To UBound(Name)
If Columns(j) = Name(i) Then Columns(j).delete
Next i
Next j
End Sub
但是,If条件不起作用。谁能帮我解决这个问题?谢谢。
答案 0 :(得分:1)
要避免循环,可以使用MATCH(或FIND)。
此外,无需将所有变量都声明为Variant
,请尽可能使用特定类型,因为这样更有效。
Sub ClearColumns()
Dim Name As Variant, i As Long, j As Long, v As Variant
Name = Array("UniqueKey", "Item Type", "Path")
For i = 0 To UBound(Name)
v = Application.Match(Name(i), Range("A1:J1"), 0) 'adjust range to suit
If IsNumeric(v) Then Columns(v).Delete
Next i
End Sub
答案 1 :(得分:0)
这实际上也可行:
Sub ClearColumns()
Dim Name As Variant, i As Variant, j As Variant
Name = Array("UniqueKey", "Item Type", "Path")
For j = 1 To 10
For i = 0 To UBound(Name)
If Columns(j).Cells(1, j) = Name(i) Then Columns(j).Cells(1, j).Delete
Next i
Next j
End Sub