我有一个带有列标题的数据表。我有不需要的列标题列表。
我想删除不需要的列标题,无论它们在工作表中的位置如何,以及用户是否可以添加其他要删除的列。
我懂了
运行时91错误
在这条线上: ws.Rows("1:1").Select.Find(T).EntireColumn.Delete
有时我会在代码的第一个循环中遇到错误,有时会遇到部分错误。
我看过其他帖子,但问题与相关性不足,无法解决问题。我尝试阅读一些有关定义对象的文章。我一直在使用msgbox命令来确保代码正在查找值,并且该代码似乎一直在工作,但是在Find命令处出现故障。
Sub DeleteBadHeaders2()
Dim FirstHeading As Range
Set FirstHeading = Worksheets("Headings_To_Delete").Range("a2")
'Worksheet that has all the column headings I want deleted
Dim x As Integer
'x is for the do while loop to individually highlight each cell
Dim y As Long
y = Worksheets("Headings_To_Delete").Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
'y acts as the upper bound to the headings to delete column for the while loop
Dim T As Variant
'T acts as a temporary value holder that will be used to delete the proper columns
Dim ws As Worksheet
Set ws = ActiveSheet
x = 0
Do While x < (y - 1)
Worksheets("Headings_To_Delete").Range("a2").Offset(x, 0).Interior.Color = RGB(224, 0, 0)
'Calling the rage as above fixes the active cell problem
Let T = Worksheets("Headings_To_Delete").Range("a2").Offset(x, 0).Value
'MsgBox T & " is found."
ws.Rows("1:1").Select.Find(T).EntireColumn.Select
'for testing switch the last part of the code to EntireColumn.Interior.Color = RGB(0, 225, 0)
x = x + 1
Loop
'The loop is highlighting the cells incrementally based on the first active cell until the upper limit of how many cells are in the column
End Sub
Run Code Online (Sandbox Code Playgroud)
ws.Rows("1:1").Select.Find(T).EntireColumn.Select
Run Code Online (Sandbox Code Playgroud)
应该
ws.Rows(1).Find(T).EntireColumn.Select 'Delete?
Run Code Online (Sandbox Code Playgroud)
通常,尽管每次使用Find()它都是一个好主意,但是Nothing在尝试执行诸如Select或之类的操作之前,先测试返回值,以检查您是否实际找到了任何东西Delete。
明确说明Find中的其他一些参数也是一个好主意lookAt,例如。
像这样:
Sub DeleteBadHeaders()
Dim r As Long, lastRow As Long
Dim T As Variant
Dim ws As Worksheet, wsList As Worksheet, f As Range
Set ws = ActiveSheet
Set wsList = Worksheets("Headings_To_Delete")
lastRow = wsList.Cells(Rows.Count, 1).End(xlUp).Row 'last row
For r = 2 To lastRow
T = wsList.Cells(r, "A").Value
If Len(T) > 0 Then
Set f = ws.Rows(1).Find(what:=T, lookat:=xlWhole)
'check to see if the heading was found
If Not f Is Nothing Then
Debug.Print "Found header '" & T & "' at " & f.Address
f.EntireColumn.Interior.Color = vbRed '<< for testing
'f.EntireColumn.Delete '<< uncomment when done testing
End If 'was found
End If 'any heading
Next r 'next in list
End Sub
Run Code Online (Sandbox Code Playgroud)