如何使Excel VBAmacros删除具有许多不同string作为标题的列?
所以我正在导入一个大的电子表格,其顶部有20到40个标题,我想自动(并快速)删除所有具有特定标题的列。 我有一个当前的代码工作,但它遍历所有列多次,每次寻找一个不同的string。 我希望它循环一次,并删除任何有任何string删除的列。
下面是我的代码的一小部分来解释更好一点:
Sub SetUpICTRP() 'MsgBox “Excel will refresh when macro is complete” Application.ScreenUpdating = False Dim c As Range Dim SrchRng As Range Dim lastColumn As Long lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column Set SrchRng = ActiveSheet.Range("A1", Cells(1, lastColumn)) Do Set c = SrchRng.Find("column", LookIn:=xlValues) If Not c Is Nothing Then c.EntireColumn.Delete Loop While Not c Is Nothing Do Set c = SrchRng.Find("Erroneous", LookIn:=xlValues) If Not c Is Nothing Then c.EntireColumn.Delete Loop While Not c Is Nothing Do Set c = SrchRng.Find("Unnecessary", LookIn:=xlValues) If Not c Is Nothing Then c.EntireColumn.Delete Loop While Not c Is Nothing Do Set c = SrchRng.Find("Not_", LookIn:=xlValues) If Not c Is Nothing Then c.EntireColumn.Delete Loop While Not c Is Nothing Application.ScreenUpdating = True End Sub
因此,目前它将删除包含短语“列”,“错误”,“不必要”和“Not_”的标题的所有列。 我真正需要的是能够find并删除“column218”,“columnadfe”,“column099”,“Not_needed”等列,而无需多次单独运行。 我认为解决scheme在于创build一个string数组,然后遍历每一列的每个string,但是我对VBA很陌生,似乎无法做到这一点。 任何帮助将是伟大的!
您可以遍历并查找单词,并使用Union()
方法将您的标题整理到单个Range对象中,然后使用.EntireColumn
方法删除与非连续单元格相关的列。
Sub SO() Dim findValue As Variant, findRange As Excel.Range, deleteRange As Excel.Range Dim findAddress As String For Each findValue In Array("column", "Erroneous", "Unnecessary", "Not_", _ "Other1", "Other2", "Other3", "etc...") Set findRange = Rows(1).EntireRow.Find(what:=findValue, LookIn:=xlValues, lookat:=xlPart) If Not findRange Is Nothing Then findAddress = findRange.Address Do If Not deleteRange Is Nothing Then Set deleteRange = Union(deleteRange, findRange) Else Set deleteRange = findRange End If Set findRange = Rows(1).EntireRow.FindNext(findRange) Loop Until findRange Is Nothing Or findRange.Address = findAddress Set findRange = Nothing End If Next findValue If deleteRange Is Nothing Then MsgBox "No columns were found for deletion!" Else deleteRange.EntireColumn.Delete End If End Sub
或者按照原来的设置,你可以使用类似于:
Sub SO() Dim c As Range, findValue As Variant For Each findValue In Array("column", "Erroneous", "Unnecessary", "Not_", _ "Other1", "Other2", "Other3", "etc...") Do Set c = Rows(1).EntireRow.Find(findValue, LookIn:=xlValues) If Not c Is Nothing Then c.EntireColumn.Delete Loop While Not c Is Nothing Next findValue End Sub