Excel / VBA:跳过错误并继续执行代码

问题:我的macros没有做我想要的。 我有一个多列的Excel文件。 我想要的是macros

  1. 寻找特定的标题(如果它们存在于文件中),那么
  2. select整个列和
  3. 按照脚本中的指定调整它的大小。 如果指定的头文件不存在,代码应该移动到下一个没有任何错误。

下面的代码将“问题描述”的大小从50改为6,虽然6是“纠正措施要求”的大小。 头部(在这种情况下不适用,因为头部不存在,因此忽略6 s / b的resize要求)。

但是那没有发生。 相反,先前条件的大小(将“问题描述”的列大小更改为50)确实变为6。

我应该使用不同的方法来写这个macros,并避免使用OnErrorResumeNext?

Sub Resize_specific_columns_OnErrResNxt() ' ' finds specific columns based on changed header names and resize them On Error Resume Next Cells.Find(what:="data domain", After:=ActiveCell, LookIn:= _ xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _ , MatchCase:=False, SearchFormat:=False).Activate ActiveCell.EntireColumn.Select Selection.ColumnWidth = 8 On Error Resume Next Cells.Find(what:="eDIM#", After:=ActiveCell, LookIn:= _ xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _ , MatchCase:=False, SearchFormat:=False).Activate ActiveCell.EntireColumn.Select Selection.ColumnWidth = 6 On Error Resume Next Cells.Find(what:="Problem Description", After:=ActiveCell, LookIn:= _ xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _ , MatchCase:=False, SearchFormat:=False).Activate ActiveCell.EntireColumn.Select Selection.ColumnWidth = 50 On Error Resume Next Cells.Find(what:="Corrective Action Required?", After:=ActiveCell, LookIn:= _ xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _ , MatchCase:=False, SearchFormat:=False).Activate ActiveCell.EntireColumn.Select Selection.ColumnWidth = 6 

On Error Resume Next恢复到下一个“行”,但3行可以合并为1:

 On Error Resume Next Cells.Find("data domain").EntireColumn.ColumnWidth = 8 Cells.Find("eDIM#").EntireColumn.ColumnWidth = 6 Cells.Find("Problem Description").EntireColumn.ColumnWidth = 50 Cells.Find("Corrective Action Required?").EntireColumn.ColumnWidth = 6 On Error Goto 0 ' optional if there is more code after that should not ignore errors 

这里有一个Find的例子,你可以复制>>粘贴这个方法到其他的。

build议使用Find是将范围设置为Find结果,然后可以检查Range = Is Nothing ,这意味着Find不成功,查找您正在查找的文本/数字。

 ' finds specific columns based on changed header names and resize them Dim FndRng As Range Set FndRng = Cells.Find(what:="data domain", After:=ActiveCell, LookIn:= _ xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _ , MatchCase:=False, SearchFormat:=False) If Not FndRng Is Nothing Then '<-- find was successful FndRng.EntireColumn.ColumnWidth = 8 End If Set FndRng = Nothing '<-- clear Range before next Find