根据标题值VBA删除列

我试图从所有的工作表中删除包含文本“标题”的列。 (这可能是标题A,标题B等)我写下面,但它不工作…请赐教。

Dim wsh As Worksheet Dim A As Range For Each wsh In ActiveWorkbook.Worksheets Do Set A = Rows(1).Find(What:="Title", LookIn:=xlValues, lookat:=xlPart) If A Is Nothing Then Exit Do A.EntireColumn.Delete Loop Next wsh 

既然你正在寻找“标题A”(以及只有“标题”),你可以使用2种方式Find

  • *通配符添加到search的string中,并在第三个参数中包含xlWhole Find(What:="Title*", LookIn:=xlValues, lookat:=xlWhole)
  • 不要使用*通配符,并使用xlPart .Find(What:="Title", LookIn:=xlValues, lookat:=xlPart)

 Option Explicit Sub RemoveTitle() Dim wsh As Worksheet Dim A As Range For Each wsh In ActiveWorkbook.Worksheets Do Set A = wsh.Rows(1).Find(What:="Title", LookIn:=xlValues, lookat:=xlPart) If Not A Is Nothing Then A.EntireColumn.Delete End If Loop While Not A Is Nothing Next wsh End Sub 

您没有使用表单来限定范围,所以只search活动表单

 Sub x() Dim wsh As Worksheet Dim A As Range For Each wsh In ActiveWorkbook.Worksheets Do Set A = wsh.Rows(1).Find(What:="Title", LookIn:=xlValues, lookat:=xlPart) If A Is Nothing Then Exit Do A.EntireColumn.Delete Loop Next wsh End Sub 

您需要指定您使用Find
并添加* (通配符)以包含所有可能性

 Dim wsh As Worksheet Dim A As Range For Each wsh In ActiveWorkbook.Worksheets Do Set A = wsh.Rows(1).Find(What:="Title*", LookIn:=xlValues, lookat:=xlPart) If A Is Nothing Then Exit Do A.EntireColumn.Delete Loop Next wsh 

您可能想要一次性删除所有列

 Option Explicit Sub main() Dim wsh As Worksheet Dim A As Range, foundTitle As Range Dim firstAddress As String For Each wsh In ActiveWorkbook.Worksheets With wsh.Range("A1", wsh.Cells(1, wsh.Cells.Columns.Count).End(xlToLeft)) Set foundTitle = .Offset(1).Resize(1, 1) Set A = .Find(What:="Title", LookIn:=xlValues, lookat:=xlPart) If Not A Is Nothing Then firstAddress = A.Address Do Set foundTitle = Union(foundTitle, A) Set A = .FindNext(A) Loop While A.Address <> firstAddress End If Set foundTitle = Intersect(foundTitle, .Cells) If Not foundTitle Is Nothing Then foundTitle.EntireColumn.Delete End With Next wsh End Sub