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

时间:2017-04-28 18:28:25

标签: excel vba excel-vba

问题:我的宏没有做我想要的。我有一个包含多列的excel文件。我想要的是宏

  1. 查找特定标题(如果它们存在于文件中),则
  2. 选择整个列和
  3. 按照脚本中的指定调整大小。如果文件中不存在指定的标头,则代码应移动到下一个标头而不会出现任何错误。
  4. 下面的代码将“问题描述”大小从50更改为6,尽管6是“需要采取纠正措施吗?”的大小。标题(在这种情况下不适用,因为该标题不存在,因此简单地忽略6 s / b的调整大小要求)。

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

    我应该使用不同的方法编写此宏并避免使用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
    

2 个答案:

答案 0 :(得分:2)

以下是您Find之一的示例,您可以复制>>将此方法粘贴到其他方法。

使用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

答案 1 :(得分:1)

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