我有一个excel文件,我想在其中删除无用的列。
假设我有4列:'ID','姓名','姓氏','工作'。我要做的是删除所有不是'ID'和'Job'的列。
我尝试使用Range.Find方法,但显然我出错了。
任何帮助表示赞赏
myArray = Array("ID", "Job")
'Delete columns which title aren't in myArray
For j = mycol To 1 Step -1 'col by col
For k = 0 To 4 'for each element in myArray
' Delete col where no elements of myArray are present.
Columns(j).Delete
Next k
Next j
编辑: 按列名称,我的意思是每列的第一行。所以A1 = ID,B1 =名称等。
答案 0 :(得分:1)
或者您可以尝试更轻松的事情:
For j = myCol To 1 Step -1 'col by col
'check if column name is in array
If IsError(Application.Match(Cells(1, j), myArray, 0)) Then
Columns(j).Delete
End If
Next j
答案 1 :(得分:0)
下面的代码将遍历所有列(根据您的mycol
值),并检查第一行中的标头是否与myArray
数组中的任何元素匹配。
Sub DeleteColumns_NotinArray()
Dim myArray
Dim j As Long, k As Long, mycol As Long
Dim ColHeadrFound As Boolean
myArray = Array("ID", "Job")
' just for my testing
mycol = 10
'Delete columns which title aren't in myArray
For j = mycol To 1 Step -1 'col by col
' reset flag
ColHeadrFound = False
For k = 0 To UBound(myArray) 'for each element in myArray
If Cells(1, j).Value = myArray(k) Then
ColHeadrFound = True
Exit For
End If
Next k
' Delete column where no elements of myArray are present
If ColHeadrFound = False Then
Columns(j).EntireColumn.Delete
End If
Next j
End Sub